我正在尝试做一个程序,它将创建一个基于文本文件的文档,到目前为止,它运行得很好。我认为,为了更容易地使用图片和其他不受支持/难以在Python中有效使用的东西。在使用完全相同的代码,但使用Doc = document()时,我使用Doc = document("template.docx")。修改后,该文件将保存到另一个docx文件。在尝试使用模板时,我会得到这些错误。创建新文档时没有错误。
回溯(最近一次调用):
File "C:\Users\bgrif\Desktop\QPA.py", line 45, in <module>
Doc.add_heading("QuizPax 28/02/2019",0)
File "C:\Users\bgrif\AppData\Local\Programs\Python\Python37-32\lib\site-packages\docx\document.py", line 39, in add_heading
return self.add_paragraph(text, style)
File "C:\Users\bgrif\AppData\Local\Programs\Python\Python37-32\lib\site-packages\docx\document.py", line 56, in add_paragraph
return self._body.add_paragraph(text, style)
File "C:\Users\bgrif\AppData\Local\Programs\Python\Python37-32\lib\site-packages\docx\blkcntnr.py", line 39, in add_paragraph
paragraph.style = style
File "C:\Users\bgrif\AppData\Local\Programs\Python\Python37-32\lib\site-packages\docx\text\paragraph.py", line 111, in style
style_or_name, WD_STYLE_TYPE.PARAGRAPH
File "C:\Users\bgrif\AppData\Local\Programs\Python\Python37-32\lib\site-packages\docx\parts\document.py", line 78, in get_style_id
return self.styles.get_style_id(style_or_name, style_type)
File "C:\Users\bgrif\AppData\Local\Programs\Python\Python37-32\lib\site-packages\docx\styles\styles.py", line 109, in get_style_id
return self._get_style_id_from_name(style_or_name, style_type)
File "C:\Users\bgrif\AppData\Local\Programs\Python\Python37-32\lib\site-packages\docx\styles\styles.py", line 139, in _get_style_id_from_name
return self._get_style_id_from_style(self[style_name], style_type)
File "C:\Users\bgrif\AppData\Local\Programs\Python\Python37-32\lib\site-packages\docx\styles\styles.py", line 53, in __getitem__
raise KeyError("no style with name '%s'" % key)
KeyError: "no style with name 'Title'"有人知道怎么解决这个问题吗?提前谢谢。
发布于 2019-03-01 19:30:18
编辑template.docx文件以添加Title样式:
Title。在Word中,大量预定义的段落样式出现在样式库和挑选列表中.这些样式的属性为Word应用程序所知,但Word在首次使用这些样式之前实际上不会将其中任何样式存储在文档中。在此之后,即使没有被任何内容使用,它们仍然保留在该文档中。
python-docx只能使用文档中定义的样式,因此您需要将该样式添加到模板文档中以使用它,而.add_heading(.., 0)调用就是这样做的。
https://stackoverflow.com/questions/54945258
复制相似问题