Creating, reading, and updating Word documents is a common need for many developers working with the Python programming language. Whether it's generating reports, manipulating existing documents, or automating document creation processes, having the ability to work with Word documents programmatically can greatly enhance productivity and efficiency. In this article, you will learn how to create, read, or update Word documents 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 command.

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

Create a Word Document from Scratch in Python

Spire.Doc for Python offers the Document class to represent a Word document model. A document must contain at least one section (represented by the Section class) and each section is a container for various elements such as paragraphs, tables, charts, and images. This example shows you how to create a simple Word document containing several paragraphs using Spire.Doc for Python.

  • Create a Document object.
  • Add a section using Document.AddSection() method.
  • Set the page margins through Section.PageSetUp.Margins property.
  • Add several paragraphs to the section using Section.AddParagraph() method.
  • Add text to the paragraphs using Paragraph.AppendText() method.
  • Create a ParagraphStyle object, and apply it to a specific paragraph using Paragraph.ApplyStyle() method.
  • Save the document to a Word file using Document.SaveToFile() method.
  • 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: Create, Read, or Update a Word Document

Read Text of a Word Document in Python

To get the text of an entire Word document, you could simply use Document.GetText() method. The following are the detailed steps.

  • Create a Document object.
  • Load a Word document using Document.LoadFromFile() method.
  • Get text from the entire document using Document.GetText() method.
  • 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: Create, Read, or Update a Word Document

Update a Word Document in Python

To access a specific paragraph, you can use the Section.Paragraphs[index] property. If you want to modify the text of the paragraph, you can reassign text to the paragraph through the Paragraph.Text property. The following are the detailed steps.

  • Create a Document object.
  • Load a Word document using Document.LoadFromFile() method.
  • Get a specific section through Document.Sections[index] property.
  • Get a specific paragraph through Section.Paragraphs[index] property.
  • Change the text of the paragraph through Paragraph.Text property.
  • Save the document to another Word file using Document.SaveToFile() method.
  • 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)

Python: Create, Read, or Update a Word Document

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.

See Also

Criar, ler e atualizar documentos do Word é uma necessidade comum para muitos desenvolvedores que trabalham com a linguagem de programação Python. Seja gerando relatórios, manipulando documentos existentes ou automatizando processos de criação de documentos, ter a capacidade de trabalhar com documentos do Word de forma programática pode aumentar muito a produtividade e a eficiência. Neste artigo você aprenderá como crie, leia ou atualize documentos do 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 do seguinte comando 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

Crie um documento do Word do zero em Python

Spire.Doc for Python oferece a classe Document para representar um modelo de documento do Word. Um documento deve conter pelo menos uma seção (representada pela classe Section) e cada seção é um contêiner para vários elementos, como parágrafos, tabelas, gráficos e imagens. Este exemplo mostra como criar um documento Word simples contendo vários parágrafos usando Spire.Doc para Python.

  • Crie um objeto Documento.
  • Adicione uma seção usando o método Document.AddSection().
  • Defina as margens da página através da propriedade Section.PageSetUp.Margins.
  • Adicione vários parágrafos à seção usando o método Section.AddParagraph().
  • Adicione texto aos parágrafos usando o método Paragraph.AppendText().
  • Crie um objeto ParagraphStyle e aplique-o a um parágrafo específico usando o método Paragraph.ApplyStyle().
  • Salve o documento em um arquivo Word usando o 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)

Python: Create, Read, or Update a Word Document

Leia o texto de um documento do Word em Python

Para obter o texto de um documento Word inteiro, você pode simplesmente usar o método Document.GetText(). A seguir estão as etapas detalhadas.

  • Crie um objeto Documento.
  • Carregue um documento do Word usando o método Document.LoadFromFile().
  • Obtenha o texto de todo o documento usando o 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)

Python: Create, Read, or Update a Word Document

Atualizar um documento do Word em Python

Para acessar um parágrafo específico, você pode usar a propriedade Section.Paragraphs[index]. Se quiser modificar o texto do parágrafo, você pode reatribuir o texto ao parágrafo por meio da propriedade Paragraph.Text. A seguir estão as etapas detalhadas.

  • Crie um objeto Documento.
  • Carregue um documento do Word usando o método Document.LoadFromFile().
  • Obtenha uma seção específica através da propriedade Document.Sections[index].
  • Obtenha um parágrafo específico através da propriedade Section.Paragraphs[index].
  • Altere o texto do parágrafo através da propriedade Paragraph.Text.
  • Salve o documento em outro arquivo do Word usando o 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)

Python: Create, Read, or Update a Word Document

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.

Veja também

Das Erstellen, Lesen und Aktualisieren von Word-Dokumenten ist für viele Entwickler, die mit der Programmiersprache Python arbeiten, ein häufiger Bedarf. Ganz gleich, ob es darum geht, Berichte zu erstellen, vorhandene Dokumente zu bearbeiten oder Dokumenterstellungsprozesse zu automatisieren: Die Möglichkeit, programmgesteuert mit Word-Dokumenten zu arbeiten, kann die Produktivität und Effizienz erheblich steigern. In diesem Artikel erfahren Sie, wie das geht Erstellen, lesen oder aktualisieren Sie Word-Dokumente in Python mit Spire.Doc for Python.

Installieren Sie Spire.Doc for Python

Dieses Szenario erfordert Spire.Doc for Python und plum-dispatch v1.7.4. Sie können mit dem folgenden pip-Befehl 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

Erstellen Sie ein Word-Dokument von Grund auf in Python

Spire.Doc for Python bietet die Document-Klasse zur Darstellung eines Word-Dokumentmodells. Ein Dokument muss mindestens einen Abschnitt enthalten (dargestellt durch die Section-Klasse) und jeder Abschnitt ist ein Container für verschiedene Elemente wie Absätze, Tabellen, Diagramme und Bilder. Dieses Beispiel zeigt Ihnen, wie Sie mit Spire.Doc für Python ein einfaches Word-Dokument mit mehreren Absätzen erstellen.

  • Erstellen Sie ein Document-Objekt.
  • Fügen Sie einen Abschnitt mit der Methode Document.AddSection() hinzu.
  • Legen Sie die Seitenränder über die Section.PageSetUp.Margins-Eigenschaft fest.
  • Fügen Sie dem Abschnitt mit der Methode Section.AddParagraph() mehrere Absätze hinzu.
  • Fügen Sie mit der Methode Paragraph.AppendText() Text zu den Absätzen hinzu.
  • Erstellen Sie ein ParagraphStyle-Objekt und wenden Sie es mit der Paragraph.ApplyStyle()-Methode auf einen bestimmten Absatz an.
  • Speichern Sie das Dokument mit der Methode Document.SaveToFile() in einer Word-Datei.
  • 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: Create, Read, or Update a Word Document

Lesen Sie den Text eines Word-Dokuments in Python

Um den Text eines gesamten Word-Dokuments abzurufen, können Sie einfach die Methode Document.GetText() verwenden. Im Folgenden finden Sie die detaillierten Schritte.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
  • Rufen Sie mit der Methode Document.GetText() Text aus dem gesamten Dokument ab..
  • 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: Create, Read, or Update a Word Document

Aktualisieren Sie ein Word-Dokument in Python

Um auf einen bestimmten Absatz zuzugreifen, können Sie die Eigenschaft Section.Paragraphs[index] verwenden. Wenn Sie den Text des Absatzes ändern möchten, können Sie dem Absatz über die Eigenschaft Paragraph.Text Text neu zuweisen. Im Folgenden finden Sie die detaillierten Schritte.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
  • Rufen Sie einen bestimmten Abschnitt über die Eigenschaft Document.Sections[index] ab.
  • Rufen Sie einen bestimmten Absatz über die Section.Paragraphs[index]-Eigenschaft ab.
  • Ändern Sie den Text des Absatzes über die Paragraph.Text-Eigenschaft.
  • Speichern Sie das Dokument mit der Methode Document.SaveToFile() in einer anderen Word-Datei.
  • 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)

Python: Create, Read, or Update a Word Document

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.

Siehe auch

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.

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)

Python: Create, Read, or Update a Word Document

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)

Python: Create, Read, or Update a Word Document

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)

Python: Create, Read, or Update a Word Document

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.

Ver también

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: Create, Read, or Update a Word Document

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: Create, Read, or Update a Word Document

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)

Python: Create, Read, or Update a Word Document

임시 라이센스 신청

생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.

또한보십시오

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.

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)

Python: Create, Read, or Update a Word Document

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)

Python: Create, Read, or Update a Word Document

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)

Python: Create, Read, or Update a Word Document

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.

Guarda anche

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.

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)

Python: Create, Read, or Update a Word Document

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)

Python: Create, Read, or Update a Word Document

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)

Python: Create, Read, or Update a Word Document

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.

Voir également

Monday, 18 December 2023 03:01

Python: Convert HTML to Word

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()

Python: Convert HTML to Word

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()

Python: Convert HTML to Word

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.

See Also

Monday, 18 December 2023 03:00

Python: converter HTML em Word

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()

Python: Convert HTML to Word

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()

Python: Convert HTML to Word

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.

Veja também

Хотя HTML предназначен для просмотра в Интернете, документы Word обычно используются для печати и физической документации. Преобразование HTML в Word гарантирует оптимизацию содержимого для печати, обеспечивая точные разрывы страниц, верхние и нижние колонтитулы и другие необходимые элементы для целей профессиональной документации. В этой статье мы объясним, как конвертируйте HTML в Word на Python с помощью Spire.Doc for 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()

Python: Convert HTML to Word

Преобразование строки 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()

Python: Convert HTML to Word

Подать заявку на временную лицензию

Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.

Смотрите также

Page 6 of 66