如何使用python-docx将样式应用于段落



我正在尝试使用python-docx模块将样式应用于文档中的段落。我可以写新的文本,但不能对以前写的段落使用不同的风格。

这里有一个例子:

x = docx.Document('Sample.docx')
x
Out[81]: <docx.api.Document at 0x121cebed0>
x.paragraphs[2].style
Out[82]: 'Normal'
x.paragraphs[2].style = 'Title'
x.paragraphs[2].style
Out[84]: 'Normal'

我无法从文档中判断这是否有效。这似乎表明段落样式是可写的,但文档中没有这种用例的示例。

请让我知道这是我的问题,还是功能尚未实现。

支持这些调用。我必须仔细查看Sample.docx才能排除故障。

如果你一步一步地打印结果,你会得到什么?

类似:

>>> document = Document('Sample.docx')
>>> document
<docx.api.Document at 0x121cebed0>  # this looks good so far
>>> paragraphs = document.paragraphs
>>> paragraphs
???
>>> paragraph = paragraphs[2]
>>> paragraph
???
>>> paragraph.style = 'Title'
>>> paragraph.style
???

此外,正确的风格名称有时也是一个技巧。我不认为这会导致你所看到的行为,但可能值得研究。你确定Sample.docx中有样式"Title"吗?

最新更新