Monday, 18 December 2023 03:24

Python: fusionar documentos de Word

Manejar una gran cantidad de documentos de Word puede resultar un gran desafío. Ya sea editando o revisando una gran cantidad de documentos, se pierde mucho tiempo abriendo y cerrando documentos. Es más, compartir y recibir una gran cantidad de documentos de Word separados puede resultar molesto, ya que puede requerir muchas operaciones repetidas de envío y recepción tanto por parte del que comparte como del receptor. Por lo tanto, para mejorar la eficiencia y ahorrar tiempo, es aconsejable fusionar documentos de Word relacionados en un solo archivo. A partir de este artículo, sabrás cómo usar Spire.Doc for Python para fácilmente fusionar documentos de Word a través de programas 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

Fusionar documentos de Word insertando archivos con Python

El método Document.insertTextFromFile() se utiliza para insertar otros documentos de Word en el actual, y el contenido insertado comenzará desde una nueva página. Los pasos detallados para fusionar documentos de Word mediante inserción son los siguientes:

  • Cree un objeto de la clase Documento y cargue un documento de Word usando el método Document.LoadFromFile().
  • Inserte el contenido de otro documento utilizando el método Document.InsertTextFromFile().
  • Guarde el documento utilizando el método Document.SaveToFile().
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of Document class and load a Word document
doc = Document()
doc.LoadFromFile("Sample1.docx")

# Insert the content from another Word document to this one
doc.InsertTextFromFile("Sample2.docx", FileFormat.Auto)

# Save the document
doc.SaveToFile("output/InsertDocuments.docx")
doc.Close()

Python: Merge Word Documents

Fusionar documentos de Word clonando contenidos con Python

También se puede fusionar documentos de Word clonando el contenido de un documento de Word a otro. Este método mantiene el formato del documento original y el contenido clonado de otro documento continúa al final del documento actual sin iniciar una nueva página. Los pasos detallados son los siguientes:

  • Cree dos objetos de la clase Documento y cargue dos documentos de Word utilizando el método Document.LoadFromFile().
  • Obtenga la última sección del documento de destino utilizando el método Document.Sections.get_Item().
  • Recorra las secciones del documento que se van a clonar y luego recorra los objetos secundarios de las secciones.
  • Obtenga un objeto secundario de sección utilizando el método Sección.Body.ChildObjects.get_Item().
  • Agregue el objeto secundario a la última sección del documento de destino utilizando el método Sección.Body.ChildObjects.Add().
  • Guarde el documento resultante utilizando el método Document.SaveToFile().
  • Python
from spire.doc import *
from spire.doc.common import *

# Create two objects of Document class and load two Word documents
doc1 = Document()
doc1.LoadFromFile("Sample1.docx")
doc2 = Document()
doc2.LoadFromFile("Sample2.docx")

# Get the last section of the first document
lastSection = doc1.Sections.get_Item(doc1.Sections.Count - 1)

# Loop through the sections in the second document
for i in range(doc2.Sections.Count):
    section = doc2.Sections.get_Item(i)
    # Loop through the child objects in the sections
    for j in range(section.Body.ChildObjects.Count):
        obj = section.Body.ChildObjects.get_Item(j)
        # Add the child objects from the second document to the last section of the first document
        lastSection.Body.ChildObjects.Add(obj.Clone())

# Save the result document
doc1.SaveToFile("output/MergeByCloning.docx")
doc1.Close()
doc2.Close()

Python: Merge Word Documents

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

Monday, 18 December 2023 03:21

Python: Word 문서 병합

많은 수의 Word 문서를 처리하는 것은 매우 어려울 수 있습니다. 많은 양의 문서를 편집하거나 검토하는 경우 문서를 열고 닫는 데 많은 시간이 낭비됩니다. 더욱이, 다수의 개별 Word 문서를 공유하고 수신하는 것은 공유자와 수신자 모두의 반복적인 전송 및 수신 작업을 많이 요구할 수 있기 때문에 성가신 일이 될 수 있습니다. 따라서 효율성을 높이고 시간을 절약하려면 다음을 수행하는 것이 좋습니다 관련 Word 문서 병합 단일 파일로. 이 기사를 통해 Spire.Doc for Python 쉽게 사용하는 방법을 알게 될 것입니다 Word 문서 병합 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 문서 병합

Document.insertTextFromFile() 메소드는 다른 Word 문서를 현재 문서에 삽입하는 데 사용되며 삽입된 내용은 새 페이지에서 시작됩니다. Word 문서를 삽입하여 병합하는 자세한 단계는 다음과 같습니다.

  • Document 클래스의 객체를 생성하고 Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
  • Document.InsertTextFromFile() 메서드를 사용하여 다른 문서의 내용을 해당 문서에 삽입합니다.
  • Document.SaveToFile() 메서드를 사용하여 문서를 저장합니다.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of Document class and load a Word document
doc = Document()
doc.LoadFromFile("Sample1.docx")

# Insert the content from another Word document to this one
doc.InsertTextFromFile("Sample2.docx", FileFormat.Auto)

# Save the document
doc.SaveToFile("output/InsertDocuments.docx")
doc.Close()

Python: Merge Word Documents

Python으로 내용을 복제하여 Word 문서 병합

Word 문서 병합은 한 Word 문서의 내용을 다른 Word 문서로 복제하여 수행할 수도 있습니다. 이 방법은 원본 문서의 서식을 유지하며 다른 문서에서 복제된 내용은 새 페이지를 시작하지 않고 현재 문서의 끝 부분에서 계속됩니다. 자세한 단계는 다음과 같습니다.

  • Document 클래스의 두 개체를 만들고 Document.LoadFromFile() 메서드를 사용하여 두 개의 Word 문서를 로드합니다.
  • Document.Sections.get_Item() 메서드를 사용하여 대상 문서의 마지막 섹션을 가져옵니다.
  • 복제할 문서의 섹션을 반복한 다음 섹션의 하위 개체를 반복합니다.
  • Section.Body.ChildObjects.get_Item() 메서드를 사용하여 섹션 하위 개체를 가져옵니다.
  • Section.Body.ChildObjects.Add() 메서드를 사용하여 대상 문서의 마지막 섹션에 하위 개체를 추가합니다.
  • Document.SaveToFile() 메서드를 사용하여 결과 문서를 저장합니다.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create two objects of Document class and load two Word documents
doc1 = Document()
doc1.LoadFromFile("Sample1.docx")
doc2 = Document()
doc2.LoadFromFile("Sample2.docx")

# Get the last section of the first document
lastSection = doc1.Sections.get_Item(doc1.Sections.Count - 1)

# Loop through the sections in the second document
for i in range(doc2.Sections.Count):
    section = doc2.Sections.get_Item(i)
    # Loop through the child objects in the sections
    for j in range(section.Body.ChildObjects.Count):
        obj = section.Body.ChildObjects.get_Item(j)
        # Add the child objects from the second document to the last section of the first document
        lastSection.Body.ChildObjects.Add(obj.Clone())

# Save the result document
doc1.SaveToFile("output/MergeByCloning.docx")
doc1.Close()
doc2.Close()

Python: Merge Word Documents

임시 라이센스 신청

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

또한보십시오

Monday, 18 December 2023 03:20

Python: unisci documenti Word

Gestire un gran numero di documenti Word può essere molto impegnativo. Che si tratti di modificare o rivedere un gran numero di documenti, si perde molto tempo nell'apertura e chiusura dei documenti. Inoltre, condividere e ricevere un gran numero di documenti Word separati può essere fastidioso, poiché potrebbe richiedere molte operazioni ripetute di invio e ricezione sia da parte di chi condivide che di chi riceve. Pertanto, per migliorare l'efficienza e risparmiare tempo, è consigliabile farlo unire documenti Word correlati in un unico file. Da questo articolo imparerai come utilizzare Spire.Doc for Python in modo semplice unire documenti Word attraverso programmi 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

Unisci documenti Word inserendo file con Python

Il metodo Document.insertTextFromFile() viene utilizzato per inserire altri documenti Word in quello corrente e il contenuto inserito inizierà da una nuova pagina. I passaggi dettagliati per unire documenti Word mediante inserimento sono i seguenti:

  • Crea un oggetto della classe Document e carica un documento Word utilizzando il metodo Document.LoadFromFile().
  • Inserisci il contenuto di un altro documento utilizzando il metodo Document.InsertTextFromFile().
  • Salva il documento utilizzando il metodo Document.SaveToFile() .
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of Document class and load a Word document
doc = Document()
doc.LoadFromFile("Sample1.docx")

# Insert the content from another Word document to this one
doc.InsertTextFromFile("Sample2.docx", FileFormat.Auto)

# Save the document
doc.SaveToFile("output/InsertDocuments.docx")
doc.Close()

Python: Merge Word Documents

Unisci documenti Word clonando i contenuti con Python

L'unione di documenti Word può essere ottenuta anche clonando i contenuti da un documento Word a un altro. Questo metodo mantiene la formattazione del documento originale e il contenuto clonato da un altro documento continua alla fine del documento corrente senza iniziare una nuova pagina. I passaggi dettagliati sono i seguenti:

  • Crea due oggetti della classe Document e carica due documenti Word utilizzando il metodo Document.LoadFromFile().
  • Ottieni l'ultima sezione del documento di destinazione utilizzando il metodo Document.Sections.get_Item().
  • Passare in rassegna le sezioni del documento da clonare, quindi scorrere gli oggetti figlio delle sezioni.
  • Ottieni un oggetto figlio della sezione utilizzando il metodo Sezione.Body.ChildObjects.get_Item().
  • Aggiungi l'oggetto figlio all'ultima sezione del documento di destinazione utilizzando il metodo Sezione.Body.ChildObjects.Add().
  • Salvare il documento risultante utilizzando il metodo Document.SaveToFile().
  • Python
from spire.doc import *
from spire.doc.common import *

# Create two objects of Document class and load two Word documents
doc1 = Document()
doc1.LoadFromFile("Sample1.docx")
doc2 = Document()
doc2.LoadFromFile("Sample2.docx")

# Get the last section of the first document
lastSection = doc1.Sections.get_Item(doc1.Sections.Count - 1)

# Loop through the sections in the second document
for i in range(doc2.Sections.Count):
    section = doc2.Sections.get_Item(i)
    # Loop through the child objects in the sections
    for j in range(section.Body.ChildObjects.Count):
        obj = section.Body.ChildObjects.get_Item(j)
        # Add the child objects from the second document to the last section of the first document
        lastSection.Body.ChildObjects.Add(obj.Clone())

# Save the result document
doc1.SaveToFile("output/MergeByCloning.docx")
doc1.Close()
doc2.Close()

Python: Merge Word Documents

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

Monday, 18 December 2023 03:19

Python : fusionner des documents Word

Traiter un grand nombre de documents Word peut s’avérer très difficile. Qu'il s'agisse d'éditer ou de réviser un grand nombre de documents, on perd beaucoup de temps à ouvrir et fermer des documents. De plus, partager et recevoir un grand nombre de documents Word distincts peut être ennuyeux, car cela peut nécessiter de nombreuses opérations d'envoi et de réception répétées de la part du partageur et du destinataire. Par conséquent, afin d’améliorer l’efficacité et de gagner du temps, il est conseillé de fusionner des documents Word associés dans un seul fichier. À partir de cet article, vous saurez comment utiliser Spire.Doc for Python pour facilement fusionner des documents Word via des programmes 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 tutoriel : Comment installer Spire.Doc for Python dans VS Code

Fusionner des documents Word en insérant des fichiers avec Python

La méthode Document.insertTextFromFile() est utilisée pour insérer d'autres documents Word dans le document actuel, et le contenu inséré démarrera à partir d'une nouvelle page. Les étapes détaillées pour fusionner des documents Word par insertion sont les suivantes :

  • Créez un objet de la classe Document et chargez un document Word à l'aide de la méthode Document.LoadFromFile().
  • Insérez-y le contenu d'un autre document à l'aide de la méthode Document.InsertTextFromFile().
  • Enregistrez le document à l'aide de la méthode Document.SaveToFile().
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of Document class and load a Word document
doc = Document()
doc.LoadFromFile("Sample1.docx")

# Insert the content from another Word document to this one
doc.InsertTextFromFile("Sample2.docx", FileFormat.Auto)

# Save the document
doc.SaveToFile("output/InsertDocuments.docx")
doc.Close()

Python: Merge Word Documents

Fusionner des documents Word en clonant le contenu avec Python

La fusion de documents Word peut également être réalisée en clonant le contenu d'un document Word à un autre. Cette méthode conserve le formatage du document d'origine et le contenu cloné à partir d'un autre document continue à la fin du document en cours sans démarrer une nouvelle page. Les étapes détaillées sont les suivantes :

  • Créez deux objets de la classe Document et chargez deux documents Word à l'aide de la méthode Document.LoadFromFile().
  • Obtenez la dernière section du document de destination à l’aide de la méthode Document.Sections.get_Item().
  • Parcourez les sections du document à cloner, puis parcourez les objets enfants des sections.
  • Obtenez un objet enfant de section à l’aide de la méthode Section.Body.ChildObjects.get_Item().
  • Ajoutez l'objet enfant à la dernière section du document de destination à l'aide de la méthode Section.Body.ChildObjects.Add().
  • Enregistrez le document résultat à l'aide de la méthode Document.SaveToFile().
  • Python
from spire.doc import *
from spire.doc.common import *

# Create two objects of Document class and load two Word documents
doc1 = Document()
doc1.LoadFromFile("Sample1.docx")
doc2 = Document()
doc2.LoadFromFile("Sample2.docx")

# Get the last section of the first document
lastSection = doc1.Sections.get_Item(doc1.Sections.Count - 1)

# Loop through the sections in the second document
for i in range(doc2.Sections.Count):
    section = doc2.Sections.get_Item(i)
    # Loop through the child objects in the sections
    for j in range(section.Body.ChildObjects.Count):
        obj = section.Body.ChildObjects.get_Item(j)
        # Add the child objects from the second document to the last section of the first document
        lastSection.Body.ChildObjects.Add(obj.Clone())

# Save the result document
doc1.SaveToFile("output/MergeByCloning.docx")
doc1.Close()
doc2.Close()

Python: Merge Word Documents

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

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