Search code examples
pythonpython-docx

Python Docx - how to number headings?


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 ?


Solution

  • 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.

    From documentation:

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

    However, if you set the heading like this:

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

    then it should default to the latent numbering style of that heading.