python - Python-docx 无法使用现有文档 - 没有名称为“标题”的样式
问题描述
我正在尝试制作一个基于文本文件创建文档的程序,到目前为止,它运行良好。我决定这样做,以便更容易地使用图像和其他不支持/难以在 Python-docx 中有效使用的东西。在使用完全相同的代码但使用 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'"
有谁知道如何解决这一问题?提前致谢。
解决方案
编辑您的template.docx
文件以添加Title
样式:
- 打开文件并按 Enter 创建一个新段落
- 选择该段落并为其指定段落样式
Title
。 - 删除该段
- 保存文件并再次尝试您的代码。
在 Word 中,大量预定义的段落样式出现在样式库和选择列表中。Word 应用程序知道这些样式的属性,但在第一次使用这些样式之前,Word 实际上不会将任何这些样式存储在文档中。之后,即使没有任何内容使用,他们也会保留该文档。
python-docx
只能使用在 document中定义的样式,因此您需要将该样式添加到模板文档中才能使用它,.add_heading(.., 0)
调用就是这样做的。
推荐阅读
- node.js - 适用于桌面和移动设备的 Material UI 和 Bootstrap
- reactjs - 在 TypeScript 中键入 Redux 工具包的存储
- docker - Azure DevOps 同一代理 (VM) 上的多个 Docker 容器
- python - 通过 Python 使用 OAuth 访问 Sharepoint 资源
- mongodb - 如果值等于某事,MongoDB 排序
- haskell - Rust 的 Read 特征的 Haskell 等价物是什么?
- node.js - 在 Ubuntu 18.04 上安装节点版本 10
- java - 如何使用 CURL 或其他 HTTP REST 客户端对 JHipster 整体 Web 应用程序(JWT 令牌)进行身份验证以使用服务
- reactjs - 使用自定义钩子在按钮单击时获取数据
- css - iOS 解决方法:在没有 CSS 属性的情况下平滑滚动 滚动行为:平滑?