Python : créer, lire ou mettre à jour un document Word
Table des matières
Installer avec Pip
pip install Spire.Doc
Liens connexes
La création, la lecture et la mise à jour de documents Word sont un besoin courant pour de nombreux développeurs travaillant avec le langage de programmation Python. Qu'il s'agisse de générer des rapports, de manipuler des documents existants ou d'automatiser des processus de création de documents, la possibilité de travailler avec des documents Word par programmation peut améliorer considérablement la productivité et l'efficacité. Dans cet article, vous apprendrez comment créer, lire ou mettre à jour des documents Word en Python à l'aide de Spire.Doc for Python.
- Créer un document Word à partir de zéro en Python
- Lire le texte d'un document Word en Python
- Mettre à jour un document Word en Python
Installer Spire.Doc for Python
Ce scénario nécessite Spire.Doc for Python et plum-dispatch v1.7.4. Ils peuvent être facilement installés dans votre VS Code via la commande pip suivante.
pip install Spire.Doc
Si vous ne savez pas comment procéder à l'installation, veuillez vous référer à ce didacticiel :Comment installer Spire.Doc for Python dans VS Code
Créer un document Word à partir de zéro en Python
Spire.Doc for Python propose la classe Document pour représenter un modèle de document Word. Un document doit contenir au moins une section (représentée par la classe Section) et chaque section est un conteneur pour divers éléments tels que des paragraphes, des tableaux, des graphiques et des images. Cet exemple vous montre comment créer un document Word simple contenant plusieurs paragraphes à l'aide de Spire.Doc pour Python.
- Créez un objet Document.
- Ajoutez une section à l'aide de la méthode Document.AddSection().
- Définissez les marges de la page via la propriété Section.PageSetUp.Margins.
- Ajoutez plusieurs paragraphes à la section à l’aide de la méthode Section.AddParagraph().
- Ajoutez du texte aux paragraphes à l’aide de la méthode Paragraph.AppendText().
- Créez un objet ParagraphStyle et appliquez-le à un paragraphe spécifique à l’aide de la méthode Paragraph.ApplyStyle().
- Enregistrez le document dans un fichier Word à l'aide de la méthode Document.SaveToFile().
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
doc = Document()
# Add a section
section = doc.AddSection()
# Set the page margins
section.PageSetup.Margins.All = 40
# Add a title
titleParagraph = section.AddParagraph()
titleParagraph.AppendText("Introduction of Spire.Doc for Python")
# Add two paragraphs
bodyParagraph_1 = section.AddParagraph()
bodyParagraph_1.AppendText("Spire.Doc for Python is a professional Python library designed for developers to " +
"create, read, write, convert, compare and print Word documents in any Python application " +
"with fast and high-quality performance.")
bodyParagraph_2 = section.AddParagraph()
bodyParagraph_2.AppendText("As an independent Word Python API, Spire.Doc for Python doesn't need Microsoft Word to " +
"be installed on neither the development nor target systems. However, it can incorporate Microsoft Word " +
"document creation capabilities into any developers' Python applications.")
# Apply heading1 to the title
titleParagraph.ApplyStyle(BuiltinStyle.Heading1)
# Create a style for the paragraphs
style2 = ParagraphStyle(doc)
style2.Name = "paraStyle"
style2.CharacterFormat.FontName = "Arial"
style2.CharacterFormat.FontSize = 13
doc.Styles.Add(style2)
bodyParagraph_1.ApplyStyle("paraStyle")
bodyParagraph_2.ApplyStyle("paraStyle")
# Set the horizontal alignment of the paragraphs
titleParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center
bodyParagraph_1.Format.HorizontalAlignment = HorizontalAlignment.Left
bodyParagraph_2.Format.HorizontalAlignment = HorizontalAlignment.Left
# Set the after spacing
titleParagraph.Format.AfterSpacing = 10
bodyParagraph_1.Format.AfterSpacing = 10
# Save to file
doc.SaveToFile("output/WordDocument.docx", FileFormat.Docx2019)

Lire le texte d'un document Word en Python
Pour obtenir le texte d’un document Word entier, vous pouvez simplement utiliser la méthode Document.GetText(). Voici les étapes détaillées.
- Créez un objet Document.
- Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
- Obtenez le texte de l’intégralité du document à l’aide de la méthode Document.GetText().
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
doc = Document()
# Load a Word file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\WordDocument.docx")
# Get text from the entire document
text = doc.GetText()
# Print text
print(text)

Mettre à jour un document Word en Python
Pour accéder à un paragraphe spécifique, vous pouvez utiliser la propriété Section.Paragraphs[index]. Si vous souhaitez modifier le texte du paragraphe, vous pouvez réaffecter du texte au paragraphe via la propriété Paragraph.Text. Voici les étapes détaillées.
- Créez un objet Document.
- Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
- Obtenez une section spécifique via la propriété Document.Sections[index].
- Obtenez un paragraphe spécifique via la propriété Section.Paragraphs[index].
- Modifiez le texte du paragraphe via la propriété Paragraph.Text.
- Enregistrez le document dans un autre fichier Word à l'aide de la méthode Document.SaveToFile().
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
doc = Document()
# Load a Word file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\WordDocument.docx")
# Get a specific section
section = doc.Sections[0]
# Get a specific paragraph
paragraph = section.Paragraphs[1]
# Change the text of the paragraph
paragraph.Text = "The title has been changed"
# Save to file
doc.SaveToFile("output/Updated.docx", FileFormat.Docx2019)

Demander une licence temporaire
Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations fonctionnelles, veuillez demander une licence d'essai de 30 jours pour toi.
Python: Convert HTML to Word
Table of Contents
Install with Pip
pip install Spire.Doc
Related Links
While HTML is designed for online viewing, Word documents are commonly used for printing and physical documentation. Converting HTML to Word ensures that the content is optimized for printing, allowing for accurate page breaks, headers, footers, and other necessary elements for professional documentation purposes. In this article, we will explain how to convert HTML to Word in Python using Spire.Doc for Python.
Install Spire.Doc for Python
This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your VS Code through the following pip commands.
pip install Spire.Doc
If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python in VS Code
Convert an HTML File to Word with Python
You can easily convert an HTML file to Word format by using the Document.SaveToFile() method provided by Spire.Doc for Python. The detailed steps are as follows.
- Create an object of the Document class.
- Load an HTML file using Document.LoadFromFile() method.
- Save the HTML file to Word format using Document.SaveToFile() method.
- Python
from spire.doc import * from spire.doc.common import * # Specify the input and output file paths inputFile = "Input.html" outputFile = "HtmlToWord.docx" # Create an object of the Document class document = Document() # Load an HTML file document.LoadFromFile(inputFile, FileFormat.Html, XHTMLValidationType.none) # Save the HTML file to a .docx file document.SaveToFile(outputFile, FileFormat.Docx2016) document.Close()

Convert an HTML String to Word with Python
To convert an HTML string to Word, you can use the Paragraph.AppendHTML() method. The detailed steps are as follows.
- Create an object of the Document class.
- Add a section to the document using Document.AddSection() method.
- Add a paragraph to the section using Section.AddParagraph() method.
- Append an HTML string to the paragraph using Paragraph.AppendHTML() method.
- Save the result document using Document.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Specify the output file path
outputFile = "HtmlStringToWord.docx"
# Create an object of the Document class
document = Document()
# Add a section to the document
sec = document.AddSection()
# Add a paragraph to the section
paragraph = sec.AddParagraph()
# Specify the HTML string
htmlString = """
<html>
<head>
<title>HTML to Word Example</title>
<style>
body {
font-family: Arial, sans-serif;
}
h1 {
color: #FF5733;
font-size: 24px;
margin-bottom: 20px;
}
p {
color: #333333;
font-size: 16px;
margin-bottom: 10px;
}
ul {
list-style-type: disc;
margin-left: 20px;
margin-bottom: 15px;
}
li {
font-size: 14px;
margin-bottom: 5px;
}
table {
border-collapse: collapse;
width: 100%;
margin-bottom: 20px;
}
th, td {
border: 1px solid #CCCCCC;
padding: 8px;
text-align: left;
}
th {
background-color: #F2F2F2;
font-weight: bold;
}
td {
color: #0000FF;
}
</style>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph demonstrating the conversion of HTML to Word document.</p>
<p>Here's an example of an unordered list:</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<p>And here's a table:</p>
<table>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr>
<td>Jacket</td>
<td>30</td>
<td>$150</td>
</tr>
<tr>
<td>Sweater</td>
<td>25</td>
<td>$99</td>
</tr>
</table>
</body>
</html>
"""
# Append the HTML string to the paragraph
paragraph.AppendHTML(htmlString)
# Save the result document
document.SaveToFile(outputFile, FileFormat.Docx2016)
document.Close()

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Python: converter HTML em Word
Índice
Instalar com Pip
pip install Spire.Doc
Links Relacionados
Embora o HTML seja projetado para visualização on-line, os documentos do Word são comumente usados para impressão e documentação física. A conversão de HTML para Word garante que o conteúdo seja otimizado para impressão, permitindo quebras de página, cabeçalhos, rodapés e outros elementos necessários para fins de documentação profissional. Neste artigo, explicaremos como converter HTML para Word em Python usando Spire.Doc for Python.
Instale Spire.Doc for Python
Este cenário requer Spire.Doc for Python e plum-dispatch v1.7.4. Eles podem ser facilmente instalados em seu VS Code por meio dos seguintes comandos pip.
pip install Spire.Doc
Se você não tiver certeza de como instalar, consulte este tutorial: Como instalar Spire.Doc for Python no código VS
Converta um arquivo HTML em Word com Python
Você pode converter facilmente um arquivo HTML para o formato Word usando o método Document.SaveToFile() fornecido por Spire.Doc for Python. As etapas detalhadas são as seguintes.
- Crie um objeto da classe Document.
- Carregue um arquivo HTML usando o método Document.LoadFromFile().
- Salve o arquivo HTML no formato Word usando o método Document.SaveToFile().
- Python
from spire.doc import * from spire.doc.common import * # Specify the input and output file paths inputFile = "Input.html" outputFile = "HtmlToWord.docx" # Create an object of the Document class document = Document() # Load an HTML file document.LoadFromFile(inputFile, FileFormat.Html, XHTMLValidationType.none) # Save the HTML file to a .docx file document.SaveToFile(outputFile, FileFormat.Docx2016) document.Close()

Convert an HTML String to Word with Python
To convert an HTML string to Word, you can use the Paragraph.AppendHTML() method. The detailed steps are as follows.
- Create an object of the Document class.
- Add a section to the document using Document.AddSection() method.
- Add a paragraph to the section using Section.AddParagraph() method.
- Append an HTML string to the paragraph using Paragraph.AppendHTML() method.
- Save the result document using Document.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Specify the output file path
outputFile = "HtmlStringToWord.docx"
# Create an object of the Document class
document = Document()
# Add a section to the document
sec = document.AddSection()
# Add a paragraph to the section
paragraph = sec.AddParagraph()
# Specify the HTML string
htmlString = """
<html>
<head>
<title>HTML to Word Example</title>
<style>
body {
font-family: Arial, sans-serif;
}
h1 {
color: #FF5733;
font-size: 24px;
margin-bottom: 20px;
}
p {
color: #333333;
font-size: 16px;
margin-bottom: 10px;
}
ul {
list-style-type: disc;
margin-left: 20px;
margin-bottom: 15px;
}
li {
font-size: 14px;
margin-bottom: 5px;
}
table {
border-collapse: collapse;
width: 100%;
margin-bottom: 20px;
}
th, td {
border: 1px solid #CCCCCC;
padding: 8px;
text-align: left;
}
th {
background-color: #F2F2F2;
font-weight: bold;
}
td {
color: #0000FF;
}
</style>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph demonstrating the conversion of HTML to Word document.</p>
<p>Here's an example of an unordered list:</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<p>And here's a table:</p>
<table>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr>
<td>Jacket</td>
<td>30</td>
<td>$150</td>
</tr>
<tr>
<td>Sweater</td>
<td>25</td>
<td>$99</td>
</tr>
</table>
</body>
</html>
"""
# Append the HTML string to the paragraph
paragraph.AppendHTML(htmlString)
# Save the result document
document.SaveToFile(outputFile, FileFormat.Docx2016)
document.Close()

Solicite uma licença temporária
Se desejar remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.
Python: конвертировать HTML в Word
Оглавление
Установить с помощью Пипа
pip install Spire.Doc
Ссылки по теме
Хотя HTML предназначен для просмотра в Интернете, документы Word обычно используются для печати и физической документации. Преобразование HTML в Word гарантирует оптимизацию содержимого для печати, обеспечивая точные разрывы страниц, верхние и нижние колонтитулы и другие необходимые элементы для целей профессиональной документации. В этой статье мы объясним, как конвертируйте HTML в Word на Python с помощью Spire.Doc for Python.
- Преобразование HTML-файла в Word с помощью Python
- Преобразование строки HTML в Word с помощью Python
Установите Spire.Doc for Python
Для этого сценария требуется Spire.Doc for Python и Plum-Dispatch v1.7.4. Их можно легко установить в ваш VS Code с помощью следующих команд pip.
pip install Spire.Doc
Если вы не знаете, как установить, обратитесь к этому руководству: Как установить Spire.Doc for Python в VS Code.
Преобразование HTML-файла в Word с помощью Python
Вы можете легко преобразовать HTML-файл в формат Word, используя метод Document.SaveToFile(), предоставляемый Spire.Doc for Python. Подробные шаги заключаются в следующем.
- Создайте объект класса Document.
- Загрузите HTML-файл с помощью метода Document.LoadFromFile().
- Сохраните HTML-файл в формате Word, используя метод Document.SaveToFile().
- Python
from spire.doc import * from spire.doc.common import * # Specify the input and output file paths inputFile = "Input.html" outputFile = "HtmlToWord.docx" # Create an object of the Document class document = Document() # Load an HTML file document.LoadFromFile(inputFile, FileFormat.Html, XHTMLValidationType.none) # Save the HTML file to a .docx file document.SaveToFile(outputFile, FileFormat.Docx2016) document.Close()

Преобразование строки HTML в Word с помощью Python
Чтобы преобразовать строку HTML в Word, вы можете использовать метод Paragraph.AppendHTML(). Подробные шаги заключаются в следующем.
- Создайте объект класса Document.
- Добавьте раздел в документ с помощью метода Document.AddSection().
- Добавьте абзац в раздел, используя метод Раздел.ДобавитьПараграф().
- Добавьте строку HTML в абзац, используя метод Paragraph.AppendHTML().
- Сохраните полученный документ с помощью метода Document.SaveToFile().
- Python
from spire.doc import *
from spire.doc.common import *
# Specify the output file path
outputFile = "HtmlStringToWord.docx"
# Create an object of the Document class
document = Document()
# Add a section to the document
sec = document.AddSection()
# Add a paragraph to the section
paragraph = sec.AddParagraph()
# Specify the HTML string
htmlString = """
<html>
<head>
<title>HTML to Word Example</title>
<style>
body {
font-family: Arial, sans-serif;
}
h1 {
color: #FF5733;
font-size: 24px;
margin-bottom: 20px;
}
p {
color: #333333;
font-size: 16px;
margin-bottom: 10px;
}
ul {
list-style-type: disc;
margin-left: 20px;
margin-bottom: 15px;
}
li {
font-size: 14px;
margin-bottom: 5px;
}
table {
border-collapse: collapse;
width: 100%;
margin-bottom: 20px;
}
th, td {
border: 1px solid #CCCCCC;
padding: 8px;
text-align: left;
}
th {
background-color: #F2F2F2;
font-weight: bold;
}
td {
color: #0000FF;
}
</style>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph demonstrating the conversion of HTML to Word document.</p>
<p>Here's an example of an unordered list:</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<p>And here's a table:</p>
<table>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr>
<td>Jacket</td>
<td>30</td>
<td>$150</td>
</tr>
<tr>
<td>Sweater</td>
<td>25</td>
<td>$99</td>
</tr>
</table>
</body>
</html>
"""
# Append the HTML string to the paragraph
paragraph.AppendHTML(htmlString)
# Save the result document
document.SaveToFile(outputFile, FileFormat.Docx2016)
document.Close()

Подать заявку на временную лицензию
Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.
Python: HTML in Word konvertieren
Inhaltsverzeichnis
Mit Pip installieren
pip install Spire.Doc
verwandte Links
Während HTML für die Online-Anzeige konzipiert ist, werden Word-Dokumente häufig zum Drucken und zur physischen Dokumentation verwendet. Durch die Konvertierung von HTML in Word wird sichergestellt, dass der Inhalt für den Druck optimiert ist und präzise Seitenumbrüche, Kopf- und Fußzeilen sowie andere notwendige Elemente für professionelle Dokumentationszwecke ermöglicht werden. In diesem Artikel erklären wir, wie das geht Konvertieren Sie HTML in Word in Python mit Spire.Doc for Python.
- Konvertieren Sie eine HTML-Datei mit Python in Word
- Konvertieren Sie einen HTML-String mit Python in Word
Installieren Sie Spire.Doc for Python
Dieses Szenario erfordert Spire.Doc for Python und plum-dispatch v1.7.4. Sie können mit den folgenden Pip-Befehlen einfach in Ihrem VS-Code installiert werden.
pip install Spire.Doc
Wenn Sie sich bei der Installation nicht sicher sind, lesen Sie bitte dieses Tutorial: So installieren Sie Spire.Doc for Python in VS Code
Konvertieren Sie eine HTML-Datei mit Python in Word
Sie können eine HTML-Datei ganz einfach in das Word-Format konvertieren, indem Sie die von Spire.Doc for Python bereitgestellte Methode Document.SaveToFile() verwenden. Die detaillierten Schritte sind wie folgt.
- Erstellen Sie ein Objekt der Document-Klasse.
- Laden Sie eine HTML-Datei mit der Methode Document.LoadFromFile().
- Speichern Sie die HTML-Datei mit der Methode Document.SaveToFile() im Word-Format.
- Python
from spire.doc import * from spire.doc.common import * # Specify the input and output file paths inputFile = "Input.html" outputFile = "HtmlToWord.docx" # Create an object of the Document class document = Document() # Load an HTML file document.LoadFromFile(inputFile, FileFormat.Html, XHTMLValidationType.none) # Save the HTML file to a .docx file document.SaveToFile(outputFile, FileFormat.Docx2016) document.Close()

Konvertieren Sie einen HTML-String mit Python in Word
Um eine HTML-Zeichenfolge in Word zu konvertieren, können Sie die Methode Paragraph.AppendHTML() verwenden. Die detaillierten Schritte sind wie folgt.
- Erstellen Sie ein Objekt der Document-Klasse.
- Fügen Sie dem Dokument mit der Methode Document.AddSection() einen Abschnitt hinzu.
- Fügen Sie dem Abschnitt mit der Methode Section.AddParagraph() einen Absatz hinzu.
- Hängen Sie mit der Methode Paragraph.AppendHTML() eine HTML-Zeichenfolge an den Absatz an.
- Speichern Sie das Ergebnisdokument mit der Methode Document.SaveToFile().
- Python
from spire.doc import *
from spire.doc.common import *
# Specify the output file path
outputFile = "HtmlStringToWord.docx"
# Create an object of the Document class
document = Document()
# Add a section to the document
sec = document.AddSection()
# Add a paragraph to the section
paragraph = sec.AddParagraph()
# Specify the HTML string
htmlString = """
<html>
<head>
<title>HTML to Word Example</title>
<style>
body {
font-family: Arial, sans-serif;
}
h1 {
color: #FF5733;
font-size: 24px;
margin-bottom: 20px;
}
p {
color: #333333;
font-size: 16px;
margin-bottom: 10px;
}
ul {
list-style-type: disc;
margin-left: 20px;
margin-bottom: 15px;
}
li {
font-size: 14px;
margin-bottom: 5px;
}
table {
border-collapse: collapse;
width: 100%;
margin-bottom: 20px;
}
th, td {
border: 1px solid #CCCCCC;
padding: 8px;
text-align: left;
}
th {
background-color: #F2F2F2;
font-weight: bold;
}
td {
color: #0000FF;
}
</style>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph demonstrating the conversion of HTML to Word document.</p>
<p>Here's an example of an unordered list:</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<p>And here's a table:</p>
<table>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr>
<td>Jacket</td>
<td>30</td>
<td>$150</td>
</tr>
<tr>
<td>Sweater</td>
<td>25</td>
<td>$99</td>
</tr>
</table>
</body>
</html>
"""
# Append the HTML string to the paragraph
paragraph.AppendHTML(htmlString)
# Save the result document
document.SaveToFile(outputFile, FileFormat.Docx2016)
document.Close()

Beantragen Sie eine temporäre Lizenz
Wenn Sie die Bewertungsmeldung aus den generierten Dokumenten entfernen oder die Funktionseinschränkungen beseitigen möchten, wenden Sie sich bitte an uns Fordern Sie eine 30-Tage-Testlizenz an für sich selbst.
Python: convertir HTML a Word
Tabla de contenido
Instalar con Pip
pip install Spire.Doc
enlaces relacionados
Si bien HTML está diseñado para visualización en línea, los documentos de Word se usan comúnmente para impresión y documentación física. La conversión de HTML a Word garantiza que el contenido esté optimizado para la impresión, lo que permite saltos de página, encabezados, pies de página y otros elementos necesarios para fines de documentación profesional. En este artículo, explicaremos cómo convertir HTML a Word en Python usando Spire.Doc for Python.
Instalar Spire.Doc for Python
Este escenario requiere Spire.Doc for Python y plum-dispatch v1.7.4. Se pueden instalar fácilmente en su código VS mediante los siguientes comandos pip.
pip install Spire.Doc
Si no está seguro de cómo instalarlo, consulte este tutorial: Cómo instalar Spire.Doc for Python en VS Code
Convertir un archivo HTML a Word con Python
Puede convertir fácilmente un archivo HTML al formato Word utilizando el método Document.SaveToFile() proporcionado por Spire.Doc for Python. Los pasos detallados son los siguientes.
- Crea un objeto de la clase Documento.
- Cargue un archivo HTML usando el método Document.LoadFromFile().
- Guarde el archivo HTML en formato Word utilizando el método Document.SaveToFile().
- Python
from spire.doc import * from spire.doc.common import * # Specify the input and output file paths inputFile = "Input.html" outputFile = "HtmlToWord.docx" # Create an object of the Document class document = Document() # Load an HTML file document.LoadFromFile(inputFile, FileFormat.Html, XHTMLValidationType.none) # Save the HTML file to a .docx file document.SaveToFile(outputFile, FileFormat.Docx2016) document.Close()

Convertir una cadena HTML a Word con Python
Para convertir una cadena HTML a Word, puede utilizar el método Paragraph.AppendHTML(). Los pasos detallados son los siguientes.
- Crea un objeto de la clase Documento.
- Agregue una sección al documento usando el método Document.AddSection().
- Agregue un párrafo a la sección usando el método Sección.AddParagraph().
- Agregue una cadena HTML al párrafo usando el método Paragraph.AppendHTML().
- Guarde el documento resultante utilizando el método Document.SaveToFile().
- Python
from spire.doc import *
from spire.doc.common import *
# Specify the output file path
outputFile = "HtmlStringToWord.docx"
# Create an object of the Document class
document = Document()
# Add a section to the document
sec = document.AddSection()
# Add a paragraph to the section
paragraph = sec.AddParagraph()
# Specify the HTML string
htmlString = """
<html>
<head>
<title>HTML to Word Example</title>
<style>
body {
font-family: Arial, sans-serif;
}
h1 {
color: #FF5733;
font-size: 24px;
margin-bottom: 20px;
}
p {
color: #333333;
font-size: 16px;
margin-bottom: 10px;
}
ul {
list-style-type: disc;
margin-left: 20px;
margin-bottom: 15px;
}
li {
font-size: 14px;
margin-bottom: 5px;
}
table {
border-collapse: collapse;
width: 100%;
margin-bottom: 20px;
}
th, td {
border: 1px solid #CCCCCC;
padding: 8px;
text-align: left;
}
th {
background-color: #F2F2F2;
font-weight: bold;
}
td {
color: #0000FF;
}
</style>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph demonstrating the conversion of HTML to Word document.</p>
<p>Here's an example of an unordered list:</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<p>And here's a table:</p>
<table>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr>
<td>Jacket</td>
<td>30</td>
<td>$150</td>
</tr>
<tr>
<td>Sweater</td>
<td>25</td>
<td>$99</td>
</tr>
</table>
</body>
</html>
"""
# Append the HTML string to the paragraph
paragraph.AppendHTML(htmlString)
# Save the result document
document.SaveToFile(outputFile, FileFormat.Docx2016)
document.Close()

Solicitar una licencia temporal
Si desea eliminar el mensaje de evaluación de los documentos generados o deshacerse de las limitaciones de la función, por favor solicitar una licencia de prueba de 30 días para ti.
Python: HTML을 Word로 변환
핍으로 설치
pip install Spire.Doc
관련된 링크들
HTML은 온라인 보기용으로 설계되었지만 Word 문서는 일반적으로 인쇄 및 실제 문서화에 사용됩니다. HTML을 Word로 변환하면 콘텐츠가 인쇄에 최적화되어 전문적인 문서화 목적에 필요한 정확한 페이지 나누기, 머리글, 바닥글 및 기타 필수 요소가 가능해집니다. 이번 글에서는 방법을 설명하겠습니다 Python에서 HTML을 Word로 변환 사용하여 Spire.Doc for Python.
Spire.Doc for Python 설치
이 시나리오에는 Spire.Doc for Python 및 Plum-dispatch v1.7.4가 필요합니다. 다음 pip 명령을 통해 VS Code에 쉽게 설치할 수 있습니다.
pip install Spire.Doc
설치 방법을 잘 모르는 경우 다음 튜토리얼을 참조하세요: VS Code에서 Spire.Doc for Python 설치하는 방법
Python을 사용하여 HTML 파일을 Word로 변환
Spire.Doc for Python에서 제공하는 Document.SaveToFile() 메서드를 사용하면 HTML 파일을 Word 형식으로 쉽게 변환할 수 있습니다. 자세한 단계는 다음과 같습니다.
- Document 클래스의 객체를 만듭니다.
- Document.LoadFromFile() 메서드를 사용하여 HTML 파일을 로드합니다.
- Document.SaveToFile() 메서드를 사용하여 HTML 파일을 Word 형식으로 저장합니다.
- Python
from spire.doc import * from spire.doc.common import * # Specify the input and output file paths inputFile = "Input.html" outputFile = "HtmlToWord.docx" # Create an object of the Document class document = Document() # Load an HTML file document.LoadFromFile(inputFile, FileFormat.Html, XHTMLValidationType.none) # Save the HTML file to a .docx file document.SaveToFile(outputFile, FileFormat.Docx2016) document.Close()

Python을 사용하여 HTML 문자열을 Word로 변환
HTML 문자열을 Word로 변환하려면 Paragraph.AppendHTML() 메서드를 사용할 수 있습니다. 자세한 단계는 다음과 같습니다.
- Document 클래스의 객체를 만듭니다.
- Document.AddSection() 메서드를 사용하여 문서에 섹션을 추가합니다.
- Section.AddParagraph() 메서드를 사용하여 섹션에 단락을 추가합니다.
- Paragraph.AppendHTML() 메서드를 사용하여 HTML 문자열을 단락에 추가합니다.
- Document.SaveToFile() 메서드를 사용하여 결과 문서를 저장합니다.
- Python
from spire.doc import *
from spire.doc.common import *
# Specify the output file path
outputFile = "HtmlStringToWord.docx"
# Create an object of the Document class
document = Document()
# Add a section to the document
sec = document.AddSection()
# Add a paragraph to the section
paragraph = sec.AddParagraph()
# Specify the HTML string
htmlString = """
<html>
<head>
<title>HTML to Word Example</title>
<style>
body {
font-family: Arial, sans-serif;
}
h1 {
color: #FF5733;
font-size: 24px;
margin-bottom: 20px;
}
p {
color: #333333;
font-size: 16px;
margin-bottom: 10px;
}
ul {
list-style-type: disc;
margin-left: 20px;
margin-bottom: 15px;
}
li {
font-size: 14px;
margin-bottom: 5px;
}
table {
border-collapse: collapse;
width: 100%;
margin-bottom: 20px;
}
th, td {
border: 1px solid #CCCCCC;
padding: 8px;
text-align: left;
}
th {
background-color: #F2F2F2;
font-weight: bold;
}
td {
color: #0000FF;
}
</style>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph demonstrating the conversion of HTML to Word document.</p>
<p>Here's an example of an unordered list:</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<p>And here's a table:</p>
<table>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr>
<td>Jacket</td>
<td>30</td>
<td>$150</td>
</tr>
<tr>
<td>Sweater</td>
<td>25</td>
<td>$99</td>
</tr>
</table>
</body>
</html>
"""
# Append the HTML string to the paragraph
paragraph.AppendHTML(htmlString)
# Save the result document
document.SaveToFile(outputFile, FileFormat.Docx2016)
document.Close()

임시 라이센스 신청
생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.
Python: converti HTML in Word
Sommario
Installa con Pip
pip install Spire.Doc
Link correlati
Mentre l'HTML è progettato per la visualizzazione online, i documenti Word vengono comunemente utilizzati per la stampa e la documentazione fisica. La conversione di HTML in Word garantisce che il contenuto sia ottimizzato per la stampa, consentendo interruzioni di pagina, intestazioni, piè di pagina e altri elementi necessari accurati per scopi di documentazione professionale. In questo articolo spiegheremo come convertire HTML in Word in Python utilizzando Spire.Doc for Python.
Installa Spire.Doc for Python
Questo scenario richiede Spire.Doc for Python e plum-dispatch v1.7.4. Possono essere facilmente installati nel tuo VS Code tramite i seguenti comandi pip.
pip install Spire.Doc
Se non sei sicuro su come installare, fai riferimento a questo tutorial: Come installare Spire.Doc for Python in VS Code
Converti un file HTML in Word con Python
Puoi convertire facilmente un file HTML in formato Word utilizzando il metodo Document.SaveToFile() fornito da Spire.Doc for Python. I passaggi dettagliati sono i seguenti.
- Crea un oggetto della classe Document.
- Carica un file HTML utilizzando il metodo Document.LoadFromFile().
- Salva il file HTML in formato Word utilizzando il metodo Document.SaveToFile().
- Python
from spire.doc import * from spire.doc.common import * # Specify the input and output file paths inputFile = "Input.html" outputFile = "HtmlToWord.docx" # Create an object of the Document class document = Document() # Load an HTML file document.LoadFromFile(inputFile, FileFormat.Html, XHTMLValidationType.none) # Save the HTML file to a .docx file document.SaveToFile(outputFile, FileFormat.Docx2016) document.Close()

Converti una stringa HTML in Word con Python
Per convertire una stringa HTML in Word, è possibile utilizzare il metodo Paragraph.AppendHTML(). I passaggi dettagliati sono i seguenti.
- Crea un oggetto della classe Document.
- Aggiungi una sezione al documento utilizzando il metodo Document.AddSection().
- Aggiungi un paragrafo alla sezione utilizzando il metodo Sezione.AddParagraph().
- Aggiungi una stringa HTML al paragrafo utilizzando il metodo Paragraph.AppendHTML().
- Salvare il documento risultante utilizzando il metodo Document.SaveToFile().
- Python
from spire.doc import *
from spire.doc.common import *
# Specify the output file path
outputFile = "HtmlStringToWord.docx"
# Create an object of the Document class
document = Document()
# Add a section to the document
sec = document.AddSection()
# Add a paragraph to the section
paragraph = sec.AddParagraph()
# Specify the HTML string
htmlString = """
<html>
<head>
<title>HTML to Word Example</title>
<style>
body {
font-family: Arial, sans-serif;
}
h1 {
color: #FF5733;
font-size: 24px;
margin-bottom: 20px;
}
p {
color: #333333;
font-size: 16px;
margin-bottom: 10px;
}
ul {
list-style-type: disc;
margin-left: 20px;
margin-bottom: 15px;
}
li {
font-size: 14px;
margin-bottom: 5px;
}
table {
border-collapse: collapse;
width: 100%;
margin-bottom: 20px;
}
th, td {
border: 1px solid #CCCCCC;
padding: 8px;
text-align: left;
}
th {
background-color: #F2F2F2;
font-weight: bold;
}
td {
color: #0000FF;
}
</style>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph demonstrating the conversion of HTML to Word document.</p>
<p>Here's an example of an unordered list:</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<p>And here's a table:</p>
<table>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr>
<td>Jacket</td>
<td>30</td>
<td>$150</td>
</tr>
<tr>
<td>Sweater</td>
<td>25</td>
<td>$99</td>
</tr>
</table>
</body>
</html>
"""
# Append the HTML string to the paragraph
paragraph.AppendHTML(htmlString)
# Save the result document
document.SaveToFile(outputFile, FileFormat.Docx2016)
document.Close()

Richiedi una licenza temporanea
Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni della funzione, per favore richiedere una licenza di prova di 30 giorni per te.
Python : convertir du HTML en Word
Table des matières
Installer avec Pip
pip install Spire.Doc
Liens connexes
Alors que le HTML est conçu pour être visualisé en ligne, les documents Word sont couramment utilisés pour l'impression et la documentation physique. La conversion HTML en Word garantit que le contenu est optimisé pour l'impression, permettant des sauts de page, des en-têtes, des pieds de page et d'autres éléments nécessaires à des fins de documentation professionnelle. Dans cet article, nous expliquerons comment convertissez du HTML en Word en Python à l'aide de Spire.Doc for Python.
Installer Spire.Doc for Python
Ce scénario nécessite Spire.Doc for Python et plum-dispatch v1.7.4. Ils peuvent être facilement installés dans votre VS Code via les commandes pip suivantes.
pip install Spire.Doc
Si vous ne savez pas comment procéder à l'installation, veuillez vous référer à ce didacticiel : Comment installer Spire.Doc for Python dans VS Code
Convertir un fichier HTML en Word avec Python
Vous pouvez facilement convertir un fichier HTML au format Word en utilisant la méthode Document.SaveToFile() fournie par Spire.Doc for Python. Les étapes détaillées sont les suivantes.
- Créez un objet de la classe Document.
- Chargez un fichier HTML à l'aide de la méthode Document.LoadFromFile().
- Enregistrez le fichier HTML au format Word à l'aide de la méthode Document.SaveToFile().
- Python
from spire.doc import * from spire.doc.common import * # Specify the input and output file paths inputFile = "Input.html" outputFile = "HtmlToWord.docx" # Create an object of the Document class document = Document() # Load an HTML file document.LoadFromFile(inputFile, FileFormat.Html, XHTMLValidationType.none) # Save the HTML file to a .docx file document.SaveToFile(outputFile, FileFormat.Docx2016) document.Close()

Convertir une chaîne HTML en Word avec Python
Pour convertir une chaîne HTML en Word, vous pouvez utiliser la méthode Paragraph.AppendHTML(). Les étapes détaillées sont les suivantes.
- Créez un objet de la classe Document.
- Ajoutez une section au document à l'aide de la méthode Document.AddSection().
- Ajoutez un paragraphe à la section à l’aide de la méthode Section.AddParagraph().
- Ajoutez une chaîne HTML au paragraphe à l’aide de la méthode Paragraph.AppendHTML().
- Enregistrez le document résultat à l'aide de la méthode Document.SaveToFile().
- Python
from spire.doc import *
from spire.doc.common import *
# Specify the output file path
outputFile = "HtmlStringToWord.docx"
# Create an object of the Document class
document = Document()
# Add a section to the document
sec = document.AddSection()
# Add a paragraph to the section
paragraph = sec.AddParagraph()
# Specify the HTML string
htmlString = """
<html>
<head>
<title>HTML to Word Example</title>
<style>
body {
font-family: Arial, sans-serif;
}
h1 {
color: #FF5733;
font-size: 24px;
margin-bottom: 20px;
}
p {
color: #333333;
font-size: 16px;
margin-bottom: 10px;
}
ul {
list-style-type: disc;
margin-left: 20px;
margin-bottom: 15px;
}
li {
font-size: 14px;
margin-bottom: 5px;
}
table {
border-collapse: collapse;
width: 100%;
margin-bottom: 20px;
}
th, td {
border: 1px solid #CCCCCC;
padding: 8px;
text-align: left;
}
th {
background-color: #F2F2F2;
font-weight: bold;
}
td {
color: #0000FF;
}
</style>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph demonstrating the conversion of HTML to Word document.</p>
<p>Here's an example of an unordered list:</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<p>And here's a table:</p>
<table>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr>
<td>Jacket</td>
<td>30</td>
<td>$150</td>
</tr>
<tr>
<td>Sweater</td>
<td>25</td>
<td>$99</td>
</tr>
</table>
</body>
</html>
"""
# Append the HTML string to the paragraph
paragraph.AppendHTML(htmlString)
# Save the result document
document.SaveToFile(outputFile, FileFormat.Docx2016)
document.Close()

Demander une licence temporaire
Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations fonctionnelles, veuillez demander une licence d'essai de 30 jours pour toi.
Python: Convert Text to Word or Word to Text
Table of Contents
Install with Pip
pip install Spire.Doc
Related Links
Text files are a common file type that contain only plain text without any formatting or styles. If you want to apply formatting or add images, charts, tables, and other media elements to text files, one of the recommended solutions is to convert them to Word files.
Conversely, if you want to efficiently extract content or reduce the file size of Word documents, you can convert them to text format. This article will demonstrate how to programmatically convert text files to Word format and convert Word files to text format using Spire.Doc for Python.
Install Spire.Doc for Python
This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your VS Code through the following pip commands.
pip install Spire.Doc
If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python in VS Code
Convert Text (TXT) to Word in Python
Conversion from TXT to Word is quite simple that requires only a few lines of code. The following are the detailed steps.
- Create a Document object.
- Load a text file using Document.LoadFromFile(string fileName) method.
- Save the text file as a Word file using Document.SaveToFile(string fileName, FileFormat fileFormat) method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a TXT file
document.LoadFromFile("input.txt")
# Save the TXT file as Word
document.SaveToFile("TxtToWord.docx", FileFormat.Docx2016)
document.Close()

Convert Word to Text (TXT) in Python
The Document.SaveToFile(string fileName, FileFormat.Txt) method provided by Spire.Doc for Python allows you to export a Word file to text format. The following are the detailed steps.
- Create a Document object.
- Load a Word file using Document.LoadFromFile(string fileName) method.
- Save the Word file in txt format using Document.SaveToFile(string fileName, FileFormat.Txt) method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file from disk
document.LoadFromFile("Input.docx")
# Save the Word file in txt format
document.SaveToFile("WordToTxt.txt", FileFormat.Txt)
document.Close()

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.