使用python docx组合word文档 [英] combine word document using python docx

查看:72
本文介绍了使用python docx组合word文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 using Python docx library.

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

For example in pywin32 library I did the following:

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)

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

But I need to do it while using Python docx library instead of win32.client

推荐答案

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

If your needs are simple, something like this might work:

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

for paragraph in source_document.paragraphs:
    text = paragraph.text
    target_document.add_paragraph(text)

您还可以做其他事情,但这应该能让您开始.

There are additional things you can do, but that should get you started.

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

It turns out that copying content from one Word file to another is quite complex in the general case, involving things like reconciling styles present in the source document that may be conflicting in the target document for example. So it's not a feature we're likely to be adding in the next year, say.

这篇关于使用python docx组合word文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆