Python Forum

Full Version: Verify if .docx table of contents is updated as per document sections or not
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Problem Statement: Verify if the Microsoft docx word document Table of Content is updated according to all Headings and sections available in the document and display final output as TOC updated or not updated.

Solution: I was searching through docx package handling of TOC but as per internet "python-docx" package lacks the possibility to verify if TOC (table of content) is updated or not.
I found below code on the internet which just updates TOC using win32com. The problem is, I am trying to find out if I can verify whether the TOC is updated or not before using 'doc.TablesOfContents(1).Update()' code.

Request you to guide.

import win32com.client
import inspect, os

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

def main():
    script_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
    file_name = 'doc_with_toc.docx'
    file_path = os.path.join(script_dir, file_name)
    update_toc(file_path)

if __name__ == "__main__":
    main()