Python Docx - how to number headings?

走远了吗. 提交于 2020-06-17 19:25:52

问题


There is a good example for Python Docx.

I have used multiple document.add_heading('xxx', level=Y) and can see when I open the generated document in MS Word that the levels are correct.

What I don't see is numbering, such a 1, 1.1, 1.1.1, etc I just see the heading text.

How can I display heading numbers, using Docx ?


回答1:


Alphanumeric heading prefixes are automatically created based on the outline style and level of the heading. Set the outline style and insert the correct level and you will get the numbering.

Numbering style has not yet been implemented. From documentation: _NumberingStyle objects class docx.styles.style._NumberingStyle[source] A numbering style. Not yet implemented.

However, if set headings (e.g., paragraph.style = document.styles['Heading 1']), then it should default to the latent numbering style of that heading.




回答2:


this answer will realy help you

first you need to new a without number header like this

paragraph = document.add_paragraph()
paragraph.style = document.styles['Heading 4']

then you will have xml word like this

<w:pPr>
<w:pStyle w:val="4"/>
</w:pPr>

then you can access xml word "pStyle" property and change it using under code

header._p.pPr.pStyle.set(qn('w:val'), u'4FDD')

final, open word file you will get what you want !!!




回答3:


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        


来源:https://stackoverflow.com/questions/53870457/python-docx-how-to-number-headings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!