合并包含所有样式的两个文档的另一种方法是使用python库docxcompose(https://pypi.org/project/docxcompose/)。我们不需要明确定义样式,也不必逐段阅读文档并将其附加到主文档中。python docxcompose的用法如下所示#Importing the required packages
from docxcompose.composer import Composer
from docx import Document as Document_compose
#filename_master is name of the file you want to merge the docx file into
master = Document_compose(filename_master)
composer = Composer(master)
#filename_second_docx is the name of the second docx file
doc2 = Document_compose(filename_second_docx)
#append the doc2 into the master using composer.append function
composer.append(doc2)
#Save the combined docx with a name
composer.save("combined.docx")
如果要将多个文档合并到一个docx文件中,可以使用下面的函数#Filename_master is the name of the file you want to merge all the document into
#files_list is a list containing all the filename of the docx file to be merged
def combine_all_docx(filename_master,files_list):
number_of_sections=len(files_list)
master = Document_compose(filename_master)
composer = Composer(master)
for i in range(0, number_of_sections):
doc_temp = Document_compose(files_list[i])
composer.append(doc_temp)
composer.save("combined_file.docx")
#For Example
#filename_master="file1.docx"
#files_list=["file2.docx","file3.docx","file4.docx",file5.docx"]
#Calling the function
#combine_all_docx(filename_master,files_list)
#This function will combine all the document in the array files_list into the file1.docx and save the merged document into combined_file.docx