Skip to content

Getting the heading number of a Word section heading #677

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
PinakiChat1 opened this issue May 20, 2019 · 3 comments
Open

Getting the heading number of a Word section heading #677

PinakiChat1 opened this issue May 20, 2019 · 3 comments

Comments

@PinakiChat1
Copy link

This is in the same line as issue #471 and #590 among many more such issues. Can you please help me in getting the number of a Word section heading? Since there a popular demand for this feature will someone implement it if it has not been implemented? Otherwise, if it has already been implemented, please let me know the technique of fetching these numbers and/or letters.

@retsyo
Copy link

retsyo commented Feb 13, 2020

any news?

@retsyo
Copy link

retsyo commented Feb 13, 2020

I made a simple one which actually does not get/read auto-generated heading number. In stead, it generates all new heading number, so the result may be different from that we read in WORD. However it meets my need

import sys
from docx import *

document = Document(r"test.docx")

MAX_HeadingLevel = 7
lstSevenZeros = [0] *MAX_HeadingLevel
lstHeadingNumber = [0] * MAX_HeadingLevel

def makeNumber():
    return '.'.join([str(i) for i in lstHeadingNumber if i])

for para in document.paragraphs:
    if para.style.name in ['Heading %i' % i for i in range(MAX_HeadingLevel)]:

        intTmp = int(para.style.name.split(' ')[1])
        lstHeadingNumber = (
            lstHeadingNumber[:intTmp-1] +
            [lstHeadingNumber[intTmp-1] + 1]
            + lstSevenZeros
        )

        text = makeNumber() + ' ' + para.text
        print('    ' * (intTmp-1), text)

@robertschulze
Copy link

Has there been any update? It should not be too difficult to implement @retsyo idea into a python-docx functionality, is it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants