Python Forum

Full Version: Сombine (Merge) word documents using python-docx
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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)
(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')