Python Docx - 如何给标题编号?

Python Docx - how to number headings?

Python Docx 有一个很好的 example

我使用了多个 document.add_heading('xxx', level=Y) 并且当我在 MS Word 中打开生成的文档时可以看到级别是正确的。

我没有看到编号,例如 1、1.1、1.1.1 等我只看到标题文本。

如何使用 Docx 显示标题编号?

字母数字标题前缀是根据标题的大纲样式和级别自动创建的。设置大纲样式并插入正确的级别,您将获得编号。

来自文档:

_NumberingStyle objects class docx.styles.style._NumberingStyle[source] A numbering style. Not yet implemented.

但是,如果您这样设置标题:

paragraph.style = document.styles['Heading 1']

那么它应该默认为该标题的潜在编号样式。

这个答案对你很有帮助

首先你需要像这样新建一个没有号码的header

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文件你会得到你想要的!!!

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