Thursday, 28 December 2017

Updating contents page in Word using python

Python Docx cannot cope with contents pages (at least at the time of writing) and from the research I have done it sound like this is something that is probably not going to happen any time soon. Luckily when searching the internet, I came across a solution (full credit to the answer posted on stack-overflow which I am struggling to re-find). The easiest, and currently only, solution that I have found is to create a word document with a contents page (and all other styles you want included) as your template.


You then open your template and populate it using python-docx and save it. You can then refresh the contents table using the following code: 

The code:

import win32com.client
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()
### End python docx as follows
#filenamedocx = r'C:\Users\garym\Documents\New folder (2)\Running_report'+datetime.datetime.today().strftime('%d%m%y')+'.docx'
#document.save(filenamedocx)
## Then run the update contents page function
update_toc(filenamedocx)

No comments:

Post a Comment