Python Forum
Сombine (Merge) word documents using python-docx - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Сombine (Merge) word documents using python-docx (/thread-26390.html)



Сombine (Merge) word documents using python-docx - Lancellot - Apr-30-2020

Hello all Hand
I'm trying to combine multiple .docx files into one using python-docx.
MKA-20-5778-0-1.docx', 'MKA-20-5967-0-1.docx this is source files, where it will be taken from content.
empty.docx - blank Word sheet.
The result of merging is saved in combined_word_documents.docx. As a result, I get an empty sheet. Why?
from docx import Document
files = ['МКА-20-5778-0-1.docx', 'МКА-20-5967-0-1.docx']


def combine_word_documents(files):
    combined_document = Document('empty.docx')
    count, number_of_files = 0, len(files)
    for file in files:
        sub_doc = Document(file)

        # Don't add a page break if you've
        # reached the last file.
        if count < number_of_files - 1:
            sub_doc.add_page_break()

        for paragraph in sub_doc.paragraphs:
            text = paragraph.text
            combined_document.add_paragraph(text)
        count += 1

    combined_document.save('combined_word_documents.docx')

combine_word_documents(files)



RE: Сombine (Merge) word documents using python-docx - toothedsword - May-12-2021

(Apr-30-2020, 05:27 AM)Lancellot Wrote: Hello all Hand
I'm trying to combine multiple .docx files into one using python-docx.
MKA-20-5778-0-1.docx', 'MKA-20-5967-0-1.docx this is source files, where it will be taken from content.
empty.docx - blank Word sheet.
The result of merging is saved in combined_word_documents.docx. As a result, I get an empty sheet. Why?
from docx import Document
files = ['МКА-20-5778-0-1.docx', 'МКА-20-5967-0-1.docx']


def combine_word_documents(files):
    combined_document = Document('empty.docx')
    count, number_of_files = 0, len(files)
    for file in files:
        sub_doc = Document(file)

        # Don't add a page break if you've
        # reached the last file.
        if count < number_of_files - 1:
            sub_doc.add_page_break()

        for paragraph in sub_doc.paragraphs:
            text = paragraph.text
            combined_document.add_paragraph(text)
        count += 1

    combined_document.save('combined_word_documents.docx')

combine_word_documents(files)


I think you can use docxcompose:

from docx import Document
from docxcompose.composer import Composer
   
master = Document("out.docx")
composer = Composer(master)
doc1 = Document("in.docx")
composer.append(doc1)
master.save('out.docx')