使用python docx组合word文档

omr*_*don 7 python python-2.7 python-docx

我有几个单词文件,每个文件都有特定的内容.我想要一个片段向我展示或帮助我弄清楚如何将word文件合并到一个文件中,同时使用Python docx库.

例如,在pywin32库中,我执行了以下操作:

rng = self.doc.Range(0, 0)
for d in data:
    time.sleep(0.05)

    docstart = d.wordDoc.Content.Start
    self.word.Visible = True
    docend = d.wordDoc.Content.End - 1
    location = d.wordDoc.Range(docstart, docend).Copy()
    rng.Paste()
    rng.Collapse(0)
    rng.InsertBreak(win32.constants.wdPageBreak)
Run Code Online (Sandbox Code Playgroud)

但我需要在使用Python docx库而不是win32.client

Mar*_*obs 14

我已经调整了上面的例子来使用最新版本的python-docx(写作时为0.8.6).请注意,这只是复制元素(元素的合并样式更复杂):

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)
Run Code Online (Sandbox Code Playgroud)

  • 这非常有用,谢谢。在我的例子中,我有很多自定义样式需要处理(但对于所有文档都是一样的),因此发现将列表中的第一个文档用作 `merged_document` 然后将所有其他文档附加到它更容易。这样就不会在样式上与默认模板发生冲突,默认模板是 `Document()` 默认使用的模板。 (2认同)

Sha*_*kla 7

合并两个文档(包括所有样式)的另一种方法是使用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")
Run Code Online (Sandbox Code Playgroud)

如果要将多个文档合并到一个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
Run Code Online (Sandbox Code Playgroud)

  • 如果有人想要在新页面上显示第二个文档,只需在上面代码中的“composer = Composer(master)”之前添加“master.add_page_break()”即可。不确定,文档的页数需要相同。 (3认同)

sca*_*nny 5

如果您的需求很简单,这样的事情可能会奏效:

source_document = Document('source.docx')
target_document = Document()

for paragraph in source_document.paragraphs:
    text = paragraph.text
    target_document.add_paragraph(text)
Run Code Online (Sandbox Code Playgroud)

您还可以执行其他操作,但这应该可以帮助您入门。

事实证明,在一般情况下,将内容从一个 Word 文件复制到另一个文件是相当复杂的,例如涉及协调源文档中存在的样式,而目标文档中可能存在冲突。所以这不是我们可能在明年添加的功能,比如说。


Joh*_*yes 5

创建一个空文档 (empty.docx) 并将两个文档添加到其中。\n在文件迭代的每个循环中,根据需要添加分页符。

\n\n

完成后,保存包含两个组合文件的新文件。

\n\n
from docx import Document\n\nfiles = ['file1.docx', 'file2.docx']\n\ndef combine_word_documents(files):\n    combined_document = Document('empty.docx')\n    count, number_of_files = 0, len(files)\n    for file in files:\n        sub_doc = Document(file)\n\n        #\xc2\xa0Don't add a page break if you've\n        #\xc2\xa0reached the last file.\n        if count < number_of_files - 1:\n            sub_doc.add_page_break()\n\n        for element in sub_doc._document_part.body._element:\n            combined_document._document_part.body._element.append(element)\n        count += 1\n\n    combined_document.save('combined_word_documents.docx')\n\ncombine_word_documents(files)\n
Run Code Online (Sandbox Code Playgroud)\n