3

我正在尝试使用 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'

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

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

4

1 回答 1

3

支持这些调用。我必须仔细查看 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 中可用的样式“标题”吗?

于 2014-04-10T05:55:54.180 回答