python-openxml / python-docx

Create and modify Word documents with Python
MIT License
4.54k stars 1.11k forks source link

Auto refresh Table of Contents using docx #1403

Open latheefS opened 4 months ago

latheefS commented 4 months ago

Hi,

I am adding new content to an existing Word document and I want an approach to auto-refresh my document's Table of contents. I've used below code but it is not showing any result and the document created out of it is struck in background process for which i had to kill from task manager.

import win32com.client

def update_toc(docx_file): word = win32com.client.DispatchEx("Word.Application") doc = word.Documents.Open(docx_file) toc_count = doc.TablesOfContents.Count if toc_count == 1: toc = doc.TablesOfContents(1) toc.Update() print('TOC should have been updated.') else: print('TOC has not been updated for sure...')

update_toc(r"C:\Users\Mydocument.docx")

Will someone help me with the details to auto refresh my word document?

beingvishalt commented 4 months ago

I also want to update TOC, but I didn't get anything.

damies13 commented 6 days ago

I also would like a solution to this issue, in my application that uses this library to generate a document I don't know if the user has MS Word, LibreOffice or some other office app installed, so workarounds like this and the one in #1207 don't really help me as they are dependent on an application outside this library