我正在使用以下脚本:
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/