有一个很好的 Python Docx 示例。
我使用了多个
document.add_heading('xxx', level=Y)
,当我在 MS Word 中打开生成的文档时,可以看到级别是正确的。
我没有看到编号,例如 1、1.1、1.1.1 等,我只看到标题文本。
如何使用 Docx 显示标题编号?
字母数字标题前缀是根据标题的大纲样式和级别自动创建的。设置轮廓样式并插入正确的级别,您将获得编号。
来自文档:
_NumberingStyle 对象类 docx.styles.style._NumberingStyle[source] 编号样式。还没有 已实施。
但是,如果您这样设置标题:
paragraph.style = document.styles['Heading 1']
那么它应该默认为该标题的潜在编号样式。
使用 python docx 有一个很好的方法可以实现标题枚举等复杂操作。以下是如何进行:
my_template.docx
。 from docx import Document
document = Document("my_template.docx")
document.add_heading('My first numbered heading', level=1)
瞧,您可以生成带有编号标题的完美文档。
这个答案对你很有帮助
首先你需要像这样新建一个没有数字的标题
paragraph = document.add_paragraph()
paragraph.style = document.styles['Heading 4']
然后你就会有这样的xml单词
<w:pPr>
<w:pStyle w:val="4"/>
</w:pPr>
然后您可以访问 xml 单词“pStyle”属性并使用代码下更改它
header._p.pPr.pStyle.set(qn('w:val'), u'4FDD')
最后,打开word文件你就会得到你想要的!!!
似乎python-docx没有提取数字标题的功能,所以我创建了它,请参阅我的github: https://github.com/nguyendangson/extract_number_heading_python-docx
def __str__(self):
if self.nivel == 1:
return str(Level.count_1)+'.- '+self.titulo
elif self.nivel==2: #Imprime si es del nivel 2
return str(Level.count_1)+'.'+str(Level.count_2)+'.- '+self.titulo
elif self.nivel==3: #Imprime si es del nivel 3
return str(Level.count_1)+'.'+str(Level.count_2)+'.'+str(Level.count_3)+'.- '+self.titulo