使用 python-docx 将内容添加到现有的 docx

add content to existing docx with python-docx

我想打开一个现有的 word 文档,我已经在其中添加了页码,然后向其中添加一些文本和标题。

这是我如何努力实现目标的基本示例

#!/usr/bin/env python 
from docx import Document
document = Document('report-template.docx')
document.add_heading('Headline No. 1', level=1)
document.add_paragraph('Test No. 1')
document.add_heading('Heading No. 2', level=2)
document.add_paragraph('Test No. 2')
document.save('example.docx')

当我对一个完整的新文档执行上述操作时,一切正常 - 当对已经存在的文件执行此操作时,它会失败并出现以下错误

Traceback (most recent call last):
  File "create-report-test.py", line 6, in <module>
    document.add_heading('Headline No. 1', level=1)
  File "/usr/lib/python2.7/site-packages/docx/document.py", line 43, in add_heading
    return self.add_paragraph(text, style)
  File "/usr/lib/python2.7/site-packages/docx/document.py", line 63, in add_paragraph
    return self._body.add_paragraph(text, style)
  File "/usr/lib/python2.7/site-packages/docx/blkcntnr.py", line 38, in add_paragraph
    paragraph.style = style
  File "/usr/lib/python2.7/site-packages/docx/text/paragraph.py", line 111, in style
    style_or_name, WD_STYLE_TYPE.PARAGRAPH
  File "/usr/lib/python2.7/site-packages/docx/parts/document.py", line 75, in get_style_id
    return self.styles.get_style_id(style_or_name, style_type)
  File "/usr/lib/python2.7/site-packages/docx/styles/styles.py", line 113, in get_style_id
    return self._get_style_id_from_name(style_or_name, style_type)
  File "/usr/lib/python2.7/site-packages/docx/styles/styles.py", line 143, in _get_style_id_from_name
    return self._get_style_id_from_style(self[style_name], style_type)
  File "/usr/lib/python2.7/site-packages/docx/styles/styles.py", line 57, in __getitem__
    raise KeyError("no style with name '%s'" % key)
KeyError: u"no style with name 'Heading 1'"

我阅读了 http://python-docx.readthedocs.org/en/latest/user/documents.html 下的文档,但似乎我遗漏了什么 - 有人知道吗?

提前致谢

python-docx 只能使用文档中已定义的样式。此错误表明未定义标题 1 段落样式。 Word 开始时没有定义任何样式(好吧,有几个像 Normal,但仅此而已),然后它会在第一次使用时将 built-in 样式添加到文件中。

两个选项:

  1. 在文档中手动添加标题 1 段落,然后将其删除。之后,标题 1 段落样式将在文档中定义。一旦 Word 添加样式,它不会删除它,即使使用该样式的所有段落都被删除。

  2. 使用python-docx自行定义标题1。有关如何执行此操作的信息,请参阅此处的文档:http://python-docx.readthedocs.org/en/latest/user/styles-using.html#define-paragraph-formatting

此页面可能也值得快速阅读以填充一些样式概念: http://python-docx.readthedocs.org/en/latest/user/styles-understanding.html

删除级别 = 1 和级别 = 2

应该给出:

document.add_heading('Headline No. 1', 1)

document.add_heading('Heading No. 2', 2)