Python: crear, leer o actualizar un documento de Word
Table des matières
Installer avec Pip
pip install Spire.Doc
Liens connexes
Crear, leer y actualizar documentos de Word es una necesidad común para muchos desarrolladores que trabajan con el lenguaje de programación Python. Ya sea generando informes, manipulando documentos existentes o automatizando procesos de creación de documentos, tener la capacidad de trabajar con documentos de Word mediante programación puede mejorar enormemente la productividad y la eficiencia. En este artículo, aprenderá cómo cree, lea o actualice documentos de Word en Python usando Spire.Doc for Python.
- Crear un documento de Word desde cero en Python
- Leer texto de un documento de Word en Python
- Actualizar un documento de Word en 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 el siguiente comando 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
Crear un documento de Word desde cero en Python
Spire.Doc for Python ofrece la clase Documento para representar un modelo de documento de Word. Un documento debe contener al menos una sección (representada por la clase Sección) y cada sección es un contenedor para varios elementos, como párrafos, tablas, gráficos e imágenes. Este ejemplo le muestra cómo crear un documento de Word simple que contenga varios párrafos usando Spire.Doc para Python.
- Crea un objeto de documento.
- Agregue una sección usando el método Document.AddSection().
- Establezca los márgenes de la página a través de la propiedad Sección.PageSetUp.Margins.
- Agregue varios párrafos a la sección usando el método Sección.AddParagraph().
- Agregue texto a los párrafos usando el método Paragraph.AppendText().
- Cree un objeto ParagraphStyle y aplíquelo a un párrafo específico utilizando el método Paragraph.ApplyStyle().
- Guarde el documento en un archivo de Word utilizando el método 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)

Leer texto de un documento de Word en Python
Para obtener el texto de un documento de Word completo, simplemente puede usar el método Document.GetText(). Los siguientes son los pasos detallados.
- Crea un objeto de documento.
- Cargue un documento de Word utilizando el método Document.LoadFromFile().
- Obtenga texto de todo el documento utilizando el método 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)

Actualizar un documento de Word en Python
Para acceder a un párrafo específico, puede utilizar la propiedad Sección.Paragrafos[índice]. Si desea modificar el texto del párrafo, puede reasignar texto al párrafo a través de la propiedad Paragraph.Text. Los siguientes son los pasos detallados.
- Crea un objeto de documento.
- Cargue un documento de Word utilizando el método Document.LoadFromFile().
- Obtenga una sección específica a través de la propiedad Document.Sections[index].
- Obtenga un párrafo específico a través de la propiedad Sección.Paragraphs[index].
- Cambie el texto del párrafo a través de la propiedad Paragraph.Text.
- Guarde el documento en otro archivo de Word utilizando el método 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)

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: Word 문서 만들기, 읽기 또는 업데이트
목차
핍으로 설치
pip install Spire.Doc
관련된 링크들
Word 문서를 만들고 읽고 업데이트하는 것은 Python 프로그래밍 언어를 사용하는 많은 개발자의 일반적인 요구 사항입니다. 보고서 생성, 기존 문서 조작, 문서 작성 프로세스 자동화 등 프로그래밍 방식으로 Word 문서를 작업할 수 있으면 생산성과 효율성이 크게 향상될 수 있습니다. 이 기사에서는 다음 방법을 배웁니다 Python에서 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에서 처음부터 Word 문서 만들기
Spire.Doc for Python Word 문서 모델을 나타내는 Document 클래스를 제공합니다. 문서에는 최소한 하나의 섹션(Section 클래스로 표시됨)이 포함되어야 하며 각 섹션은 단락, 표, 차트, 이미지 등 다양한 요소에 대한 컨테이너입니다. 이 예에서는 Python용 Spire.Doc을 사용하여 여러 단락이 포함된 간단한 Word 문서를 만드는 방법을 보여줍니다.
- 문서 개체를 만듭니다.
- Document.AddSection() 메서드를 사용하여 섹션을 추가합니다.
- Section.PageSetUp.Margins 속성을 통해 페이지 여백을 설정합니다.
- Section.AddParagraph() 메서드를 사용하여 섹션에 여러 단락을 추가합니다.
- Paragraph.AppendText() 메서드를 사용하여 단락에 텍스트를 추가합니다.
- ParagraphStyle 객체를 생성하고 Paragraph.ApplyStyle() 메서드를 사용하여 특정 단락에 적용합니다.
- Document.SaveToFile() 메서드를 사용하여 문서를 Word 파일에 저장합니다.
- 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)

Python에서 Word 문서의 텍스트 읽기
전체 Word 문서의 텍스트를 얻으려면 Document.GetText() 메서드를 사용하면 됩니다. 자세한 단계는 다음과 같습니다.
- 문서 개체를 만듭니다.
- Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
- 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)

Python에서 Word 문서 업데이트
특정 단락에 액세스하려면 Section.Paragraphs[index] 속성을 사용할 수 있습니다. 단락의 텍스트를 수정하려면 Paragraph.Text 속성을 통해 단락에 텍스트를 다시 할당할 수 있습니다. 자세한 단계는 다음과 같습니다.
- 문서 개체를 만듭니다.
- Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
- Document.Sections[index] 속성을 통해 특정 섹션을 가져옵니다.
- Section.Paragraphs[index] 속성을 통해 특정 단락을 가져옵니다.
- Paragraph.Text 속성을 통해 단락의 텍스트를 변경합니다.
- Document.SaveToFile() 메서드를 사용하여 문서를 다른 Word 파일에 저장합니다.
- 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)

임시 라이센스 신청
생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.
Python: crea, leggi o aggiorna un documento Word
Sommario
Installa con Pip
pip install Spire.Doc
Link correlati
Creare, leggere e aggiornare documenti Word è un'esigenza comune per molti sviluppatori che lavorano con il linguaggio di programmazione Python. Che si tratti di generare report, manipolare documenti esistenti o automatizzare i processi di creazione di documenti, avere la capacità di lavorare con documenti Word a livello di codice può migliorare notevolmente la produttività e l'efficienza. In questo articolo imparerai come farlo creare, leggere o aggiornare documenti Word in Python utilizzando Spire.Doc for Python.
- Crea un documento Word da zero in Python
- Leggere il testo di un documento Word in Python
- Aggiorna un documento Word in 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 il seguente comando 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
Crea un documento Word da zero in Python
Spire.Doc for Python offre la classe Document per rappresentare un modello di documento Word. Un documento deve contenere almeno una sezione (rappresentata dalla classe Sezione) e ogni sezione è un contenitore per vari elementi come paragrafi, tabelle, grafici e immagini. Questo esempio mostra come creare un semplice documento Word contenente diversi paragrafi utilizzando Spire.Doc per Python.
- Creare un oggetto Documento.
- Aggiungi una sezione utilizzando il metodo Document.AddSection().
- Imposta i margini della pagina tramite la proprietà Sezione.PageSetUp.Margins.
- Aggiungi diversi paragrafi alla sezione utilizzando il metodo Sezione.AddParagraph().
- Aggiungi testo ai paragrafi utilizzando il metodo Paragraph.AppendText().
- Crea un oggetto ParagraphStyle e applicalo a un paragrafo specifico utilizzando il metodo Paragraph.ApplyStyle().
- Salva il documento in un file Word utilizzando il metodo 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)

Leggere il testo di un documento Word in Python
Per ottenere il testo di un intero documento Word, puoi semplicemente utilizzare il metodo Document.GetText(). Di seguito sono riportati i passaggi dettagliati.
- Creare un oggetto Documento.
- Carica un documento Word utilizzando il metodo Document.LoadFromFile().
- Ottieni testo dall'intero documento utilizzando il metodo 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)

Aggiorna un documento Word in Python
Per accedere a un paragrafo specifico, è possibile utilizzare la proprietà Sezione.Paragraphs[indice]. Se desideri modificare il testo del paragrafo, puoi riassegnare il testo al paragrafo tramite la proprietà Paragraph.Text. Di seguito sono riportati i passaggi dettagliati.
- Creare un oggetto Documento.
- Carica un documento Word utilizzando il metodo Document.LoadFromFile().
- Ottieni una sezione specifica tramite la proprietà Document.Sections[index].
- Ottieni un paragrafo specifico tramite la proprietà Sezione.Paragraphs[indice].
- Modificare il testo del paragrafo tramite la proprietà Paragraph.Text.
- Salva il documento in un altro file Word utilizzando il metodo 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)

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 : 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일 평가판 라이센스 요청 자신을 위해.