0

我有一个只有文本的 docx 文件。我想创建一个新的 docx 文件,其中仅包含原始 docx 中页面的一部分。我为此使用 python-docx。到目前为止,我已经能够遍历原始 docx 文档并将原始文档中的每个所需段落/运行复制到新文档中,如下所示(我相信这个例子应该制作一个精确的副本):

Doc = docx.Document('/tmp/input.docx')
OutDoc = docx.Document()

for para in Doc.paragraphs:
    currentParagraph = OutDoc.add_paragraph(style=para.style)
    for run in para.runs:
        currentParagraph.add_run(run.text, style=run.style)
OutDoc.save('/tmp/output.docx')

尽管我正在复制所有样式信息,但我似乎遗漏了一些东西,因为输出缺少一些格式。

4

1 回答 1

1

在 Word 中,如果新文档中未明确定义该样式,则忽略应用于段落或运行(或任何其他内容)的样式名称。

您可以解析源文档中的样式并在新文档中重新创建每个样式,或者为已包含所需样式的新文档创建一个空白“模板”文档。

“默认”python-docx 文档模板包含许多内置样式,但如果您的文档使用任何自定义样式,则可以解释您所看到的症状。

有关更多信息,请参阅文档中的这些页面:http: //python-docx.readthedocs.org/en/latest/user/styles-understanding.html http://python-docx.readthedocs.org/en/latest/user/样式-using.html http://python-docx.readthedocs.org/en/latest/api/document.html#docx.document.Document.styles http://python-docx.readthedocs.org/en/latest/ api/style.html

于 2015-07-16T21:53:09.923 回答