S
S
Stepan Sidorov2020-12-25 12:31:51
Word
Stepan Sidorov, 2020-12-25 12:31:51

How to auto-create table of contents in word (OOXML tag)?

Hello.
I am writing a .docx exporter in python.
And at the final stage of writing, all I had to do was make a table of contents.
I found how to make a ToC (table of contetns) element:

fldChar = OxmlElement('w:fldChar')  # creates a new element
fldChar.set(qn('w:fldCharType'), 'begin')  # sets attribute on element
fldChar.set(qn('w:dirty'), 'true')
instrText = OxmlElement('w:instrText')
instrText.set(qn('xml:space'), 'preserve')  # sets attribute on element
instrText.text = r'TOC \o "1-3" \h \z \u' # change 1-3 depending on heading levels you need
fldChar2 = OxmlElement('w:fldChar')
fldChar2.set(qn('w:fldCharType'), 'separate')
fldChar3 = OxmlElement('w:t')
fldChar3.text = "Right-click to update field."
fldChar2.append(fldChar3)

fldChar4 = OxmlElement('w:fldChar')
fldChar4.set(qn('w:fldCharType'), 'end')

r_element = run._r
r_element.append(fldChar)
r_element.append(instrText)
r_element.append(fldChar2)
r_element.append(fldChar4)

To update this table of contents I found this one:

word = win32com.client.DispatchEx("Word.Application")
doc = word.Documents.Open(docx_file)
doc.TablesOfContents(1).Update()
doc.Close(SaveChanges=True)
word.Quit()

This code only works for windows. the win32com library is used .

Accordingly, I need another solution.
I read that there is a special tag in the table of contents that, when the document is opened, updates the table of contents itself, thereby generating it.

I'm not sure what it is, if there is, then the question is: what is this tag?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question