Search code examples
pythonpython-3.xdocxpython-docx

How to create/modify dynamic Table of Contents in MS word by using python


everyone.I am writing a python script that can take a xml file to generate MS-Word automatically. I am using python library docxtpl to do this work.

For example, if my script take xml like this:

<?xml version="1.0" encoding="UTF-8"?>
<Test>
<egg type="Text">some normal text.</egg>
<apple type="RichText" font="Times New Roman" color="#ff00ff" bold="True">This is a very big apple.</apple>
<banana type="Inline image" width='500' height='400'>D:\Tannis\Format_Bot\image\174324.jpg</banana>
<orange type="Replace picture" target="target.jpg">D:\Tannis\Format_Bot\image\source.jpg</orange>
</test>

Then my script can insert those text/picture or replace picture in MS-Word. For now my script can handle text/picture/table/header/footer.

But I don't know how to create/modify Table of Contents(ToC) of MS-Word. For example, my contents of MS-word may be dynamic, some are more and some are less. In such case my ToC must change dynamically.

It seems docxtpl can't handle this work. I google this question but no good solution for me.

Does anyone can figure out some solution? Use other python library is find, I will learn.

Any help would be appreciate, Thanks!


Solution

  • Basically You don't have to create/modify the Table of Contents. Follow the below steps and you will be fine :

    • Insert a dummy Table of contents that is automatically by MS Word in your template.
    • What this dummy toc does is, when you right click and select update fields, it will generate the table of contents automatically. All you have to do is use heading elements to indicate that you are creating a bookmark-able element.
    • After you generate the document with docxtpl, open it and right click on toc, select update fields.
    • Hola! Your table of contents is updated without much pain.

    docxtpl is great. But stop thinking that you have to do everything by using just docxtpl. Let MS Word do the things which it is better at doing.

    docxtpl is under development. So the above said way is your best bet. I'm using the same method in one of my projects. Works totally fine.