我正在使用 python-docx 0.7.6。
我似乎无法弄清楚如何为某个段落设置字体系列和大小。
.style
有财产但不style="Times New Roman"
工作。
有人可以给我举个例子吗?
谢谢。
我正在使用 python-docx 0.7.6。
我似乎无法弄清楚如何为某个段落设置字体系列和大小。
.style
有财产但不style="Times New Roman"
工作。
有人可以给我举个例子吗?
谢谢。
这是如何将Normal
样式设置为 fontArial
和 size 10pt
。
from docx.shared import Pt
style = document.styles['Normal']
font = style.font
font.name = 'Arial'
font.size = Pt(10)
这就是如何将其应用于paragraph
.
paragraph.style = document.styles['Normal']
使用当前版本的 python-docx (0.8.5)。
在阅读了API 文档之后,我能够弄清楚如何创建自己的样式并应用它。您可以通过更改此代码以使用 WD_STYLE_TYPE.PARAGRAPH 以相同的方式创建段落样式对象。我花了一分钟才弄清楚对象以及它们的应用级别,因此请确保您清楚地理解这一点。我发现与直觉相反的是,您在创建样式属性后对其进行定义。
这就是我创建字符级样式对象的方式。
document = Document(path to word document)
# 创建一个字符级样式对象(“CommentsStyle”)然后定义它的参数
obj_styles = document.styles
obj_charstyle = obj_styles.add_style('CommentsStyle', WD_STYLE_TYPE.CHARACTER)
obj_font = obj_charstyle.font
obj_font.size = Pt(10)
obj_font.name = 'Times New Roman'
这就是我将样式应用于跑步的方式。
paragraph.add_run(any string variable, style = 'CommentsStyle').bold = True
最新版本的 python-docx 中添加了对运行样式的支持
python-docx 的文档在这里: http: //python-docx.readthedocs.org/en/latest/
默认模板中可用的样式在此处列出:http: //python-docx.readthedocs.org/en/latest/user/styles.html
在上面的示例中,您使用了字体名称(“Times New Roman”)而不是样式 ID。例如,如果您使用“Heading1”,这将改变字体的外观,除其他外,因为它是一种段落样式。
目前没有用于直接将字体名称或字体大小应用到 python-docx 中的文本的 API,尽管可能在一个月内,下一个版本中会推出更多功能。同时,您可以定义段落样式和所需的字符设置并应用这些样式。使用样式是在 Word 中应用格式的推荐方法,类似于 CSS 是在 HTML 中应用格式的推荐方法。
使用此代码将对您有很大帮助。
import docx
from docx.shared import Pt
from docx.enum.style import WD_STYLE_TYPE
doc = docx.Document()
parag = doc.add_paragraph("Hello!")
font_styles = doc.styles
font_charstyle = font_styles.add_style('CommentsStyle', WD_STYLE_TYPE.CHARACTER)
font_object = font_charstyle.font
font_object.size = Pt(20)
font_object.name = 'Times New Roman'
parag.add_run("this word document, was created using Times New Roman", style='CommentsStyle').bold = True
parag.add_run("Python", style='CommentsStyle').italic = True
doc.save("test.docx")