Skip to main content
 首页 » 编程设计

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

2024年11月01日13mayingbao

我正在尝试使用 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 中有可用的样式“标题”吗?