我正在尝试制作一个程序,该程序将基于文本文件创建文档,到目前为止,它运行良好。我决定,使使用图像和其他不支持/难以在Python-Docx中使用的图像和其他东西变得更加容易。使用完全相同的代码,而是使用doc = document()我使用doc = document(" template.docx")。修改后,将文件保存到其他DOCX文件。尝试使用模板时会遇到这些错误。创建新文档时没有错误。
追溯(最近的最新电话):
File "C:UsersbgrifDesktopQPA.py", line 45, in <module>
Doc.add_heading("QuizPax 28/02/2019",0)
File "C:UsersbgrifAppDataLocalProgramsPythonPython37-32libsite-packagesdocxdocument.py", line 39, in add_heading
return self.add_paragraph(text, style)
File "C:UsersbgrifAppDataLocalProgramsPythonPython37-32libsite-packagesdocxdocument.py", line 56, in add_paragraph
return self._body.add_paragraph(text, style)
File "C:UsersbgrifAppDataLocalProgramsPythonPython37-32libsite-packagesdocxblkcntnr.py", line 39, in add_paragraph
paragraph.style = style
File "C:UsersbgrifAppDataLocalProgramsPythonPython37-32libsite-packagesdocxtextparagraph.py", line 111, in style
style_or_name, WD_STYLE_TYPE.PARAGRAPH
File "C:UsersbgrifAppDataLocalProgramsPythonPython37-32libsite-packagesdocxpartsdocument.py", line 78, in get_style_id
return self.styles.get_style_id(style_or_name, style_type)
File "C:UsersbgrifAppDataLocalProgramsPythonPython37-32libsite-packagesdocxstylesstyles.py", line 109, in get_style_id
return self._get_style_id_from_name(style_or_name, style_type)
File "C:UsersbgrifAppDataLocalProgramsPythonPython37-32libsite-packagesdocxstylesstyles.py", line 139, in _get_style_id_from_name
return self._get_style_id_from_style(self[style_name], style_type)
File "C:UsersbgrifAppDataLocalProgramsPythonPython37-32libsite-packagesdocxstylesstyles.py", line 53, in __getitem__
raise KeyError("no style with name '%s'" % key)
KeyError: "no style with name 'Title'"
有人知道如何解决这个问题吗?预先感谢。
编辑您的template.docx
文件以添加Title
样式:
- 打开文件并通过击中Enter 创建新段落
- 选择该段落并分配段落样式
Title
。 - 删除该段
- 保存文件并再次尝试您的代码。
在Word中,样式画廊和挑选列表中出现了大量预定段落样式。这些样式的属性是"应用程序"一词已知的,但是在第一次使用之前,Word实际上并未将这些样式存储在文档中。之后,他们即使没有任何内容都没有使用该文档。
python-docx
只能与文档中定义的样式中的样式一起使用,因此您需要将该样式添加到模板文档中以使用它,而.add_heading(.., 0)
调用可以。