combine word document using python docx

前端 未结 6 1895
陌清茗
陌清茗 2020-12-06 05:54

I have few word files that each have specific content. I would like for a snippet that show me or help me to figure out how to combine the word files into one file, while us

6条回答
  •  旧巷少年郎
    2020-12-06 06:41

    I've adjusted the example above to work with the latest version of python-docx (0.8.6 at the time of writing). Note that this just copies the elements (merging styles of elements is more complicated to do):

    from docx import Document
    
    files = ['file1.docx', 'file2.docx']
    
    def combine_word_documents(files):
        merged_document = Document()
    
        for index, file in enumerate(files):
            sub_doc = Document(file)
    
            # Don't add a page break if you've reached the last file.
            if index < len(files)-1:
               sub_doc.add_page_break()
    
            for element in sub_doc.element.body:
                merged_document.element.body.append(element)
    
        merged_document.save('merged.docx')
    
    combine_word_documents(files)
    

提交回复
热议问题