python-2.7 - 无法使用 docx 更改 "heading 1"字体名称

标签 python-2.7 python-docx

我正在使用以下脚本:

header = self.document.add_paragraph(style='Heading 1')
header.style.font.name = 'Arial'
header.style.font.size = Pt(16)
header.add_run('Header One')

结果是“Header One”得到“Calibri”。

最佳答案

即使对于 python-docx 版本 0.8.5,这也是一个合法的错误。如果您要更改“Normal”样式的字体名称,它可以工作(如 python-docx 手册上的示例所示),但这不适用于“Heading 1”样式。

一种解决方法是创建一个新的标题样式,将标题 1 作为基本样式,然后修改新样式的字体名称和大小:

from docx.enum.style import WD_STYLE_TYPE

styles = self.document.styles
new_heading_style = styles.add_style('New Heading', WD_STYLE_TYPE.PARAGRAPH)
new_heading_style.base_style = styles['Heading 1']
font = new_heading_style.font
font.name = 'Arial'
font.size = Pt(16)
self.document.add_paragraph('Header One', style='New Heading')

关于python-2.7 - 无法使用 docx 更改 "heading 1"字体名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37220754/

相关文章:

python - 学习 : How to apply dimensionality reduction on huge data set?

python-docx - 在 python docx 中创建表格并加粗文本

python - 如何将dataFrame中的groupby分组表写入word文档?

python-2.7 - 为什么我从 google adwords api 收到 CERTIFICATE_VERIFY_FAILED?

python - 从 docx 文件中删除所有图像

python - 从 MS Word 中的表格中识别图像文件

python - 表解析,将图像、图表等从一个 docx 复制到新的 docx - Python

django - 在 Python 2.7 中使用 unicode_literals 时在 Django 中解码 utf-8

python-2.7 - Python 脚本被 SIGKILL 终止而不是抛出 MemoryError

python - 如何在 python 中处理 cpu 缓存(或调用一次函数的最快方法)