Last modified: Jul 08, 2026

Generate Table of Contents in DOCX with Python

Creating a table of contents (TOC) in a Word document by hand is tedious. Python makes it easy. You can automate TOC generation with the python-docx library. This article shows you how.

We will cover the entire process. You will learn to add headings. Then you will insert a TOC field. Finally, you will update it. Let's start.

Why Automate TOC Generation?

Manual TOC creation is error-prone. You must update page numbers. You must check heading levels. Python automation solves these problems. It saves time and ensures accuracy.

Automation is especially useful for large documents. Think of reports, manuals, or books. A script can generate a TOC in seconds. This is much faster than doing it by hand.

For best results, follow Python docx Best Practices for Clean Generation. Clean code leads to clean documents. You can read more about it in our Python docx Best Practices for Clean Generation guide.

Setting Up Your Environment

First, install the required libraries. You need python-docx. Open your terminal and run:


pip install python-docx

That's it. You are ready to code. We will use a simple script. It will create a document with headings and a TOC.

Creating Headings for the TOC

A TOC works with headings. The python-docx library lets you add headings easily. Use the add_heading method. Each heading should have a level. Level 1 is for main sections. Level 2 is for subsections.

Here is an example:


from docx import Document

doc = Document()

# Add headings for TOC
doc.add_heading('Introduction', level=1)
doc.add_paragraph('This is the introduction section.')

doc.add_heading('Getting Started', level=1)
doc.add_paragraph('How to begin the process.')

doc.add_heading('Installation', level=2)
doc.add_paragraph('Steps to install the software.')

doc.add_heading('Configuration', level=2)
doc.add_paragraph('Configuring the settings.')

doc.add_heading('Advanced Topics', level=1)
doc.add_paragraph('Deep dive into complex features.')

doc.save('document_with_headings.docx')

This script creates a document with five headings. The TOC will use these headings. Make sure your headings are well-structured. This ensures a clean TOC.

Inserting a Table of Contents Field

Now, we insert the TOC field. The python-docx library does not have a direct TOC method. But we can add a Word field code. This tells Word to generate the TOC.

We use the add_field method. The field code is 'TOC \\o "1-3" \\h \\z \\u'. This creates a TOC for headings level 1 to 3. It also includes hyperlinks.

Let's add it to our document. Insert it at the beginning, before the headings.


from docx import Document
from docx.oxml.ns import qn

doc = Document()

# Insert a TOC field at the start
paragraph = doc.add_paragraph()
run = paragraph.add_run()
fldChar1 = run._r.makeelement(qn('w:fldChar'), {qn('w:fldCharType'): 'begin'})
run._r.append(fldChar1)

run2 = paragraph.add_run()
instrText = run2._r.makeelement(qn('w:instrText'), {})
instrText.text = ' TOC \\o "1-3" \\h \\z \\u '
run2._r.append(instrText)

run3 = paragraph.add_run()
fldChar2 = run3._r.makeelement(qn('w:fldChar'), {qn('w:fldCharType'): 'end'})
run3._r.append(fldChar2)

# Add headings
doc.add_heading('Introduction', level=1)
doc.add_paragraph('This is the introduction section.')

doc.add_heading('Getting Started', level=1)
doc.add_paragraph('How to begin the process.')

doc.add_heading('Installation', level=2)
doc.add_paragraph('Steps to install the software.')

doc.add_heading('Configuration', level=2)
doc.add_paragraph('Configuring the settings.')

doc.add_heading('Advanced Topics', level=1)
doc.add_paragraph('Deep dive into complex features.')

doc.save('document_with_toc.docx')

This code inserts a TOC field. When you open the document in Word, the TOC will appear. You may need to update it. Right-click the TOC and select "Update Field".

This method works well. But it requires manual updating. For full automation, you can use win32com to update the TOC. However, that is platform-specific. For more details, see our comparison: Python docx vs win32com: Automate Word Docs.

Updating the TOC Automatically

If you need the TOC to update automatically, use win32com. This works only on Windows. It interacts with Microsoft Word directly.

Here is an example:


import win32com.client as win32

# Open the document
word = win32.gencache.EnsureDispatch('Word.Application')
word.Visible = False
doc = word.Documents.Open('C:\\path\\to\\document_with_toc.docx')

# Update the TOC
for field in doc.Fields:
    if field.Type == 15:  # TOC field type
        field.Update()

# Save and close
doc.Save()
doc.Close()
word.Quit()

This script updates all TOC fields. It ensures the page numbers and headings are correct. Use this after generating the document with python-docx.

For complex documents, you might need pagination control. Check our Python DOCX Pagination Control Guide for tips on managing page breaks.

Handling Multiple Heading Levels

Your TOC can include multiple heading levels. The field code 'TOC \\o "1-3"' includes levels 1 to 3. You can change this range. For example, 'TOC \\o "1-2"' includes only levels 1 and 2.

Make sure your document uses consistent heading styles. Use add_heading with the correct level. This ensures the TOC picks up all headings.

Here is an example with three levels:


doc.add_heading('Chapter 1', level=1)
doc.add_heading('Section 1.1', level=2)
doc.add_heading('Subsection 1.1.1', level=3)

The TOC will show all these headings. This is useful for detailed documents.

Customizing the TOC Appearance

The TOC appearance is controlled by Word styles. You can modify the 'TOC 1', 'TOC 2', etc., styles. This changes the font, size, and indentation.

In python-docx, you can modify styles. But it is easier to use a template. Create a Word document with your desired TOC styles. Then use it as a template.

For template-based automation, see our Python DOCX Templates with Jinja2 guide. This approach is powerful for complex documents.

Complete Example with Output

Let's put everything together. Here is a complete script. It creates a document with a TOC.


from docx import Document
from docx.oxml.ns import qn

doc = Document()

# Add title
doc.add_heading('My Report', level=0)

# Insert TOC field
paragraph = doc.add_paragraph()
run = paragraph.add_run()
fldChar1 = run._r.makeelement(qn('w:fldChar'), {qn('w:fldCharType'): 'begin'})
run._r.append(fldChar1)

run2 = paragraph.add_run()
instrText = run2._r.makeelement(qn('w:instrText'), {})
instrText.text = ' TOC \\o "1-2" \\h \\z \\u '
run2._r.append(instrText)

run3 = paragraph.add_run()
fldChar2 = run3._r.makeelement(qn('w:fldChar'), {qn('w:fldCharType'): 'end'})
run3._r.append(fldChar2)

# Add headings
doc.add_heading('Introduction', level=1)
doc.add_paragraph('Welcome to the report.')

doc.add_heading('Methodology', level=1)
doc.add_paragraph('We used a systematic approach.')

doc.add_heading('Data Collection', level=2)
doc.add_paragraph('Data was collected from surveys.')

doc.add_heading('Analysis', level=2)
doc.add_paragraph('We performed statistical analysis.')

doc.add_heading('Results', level=1)
doc.add_paragraph('The results are promising.')

doc.save('complete_report.docx')
print('Document created successfully.')

When you open the document in Word, you will see the TOC. Update it by right-clicking and selecting "Update Field". The output will look like this:


Document created successfully.

Inside the document, the TOC will list all headings. It will include page numbers and hyperlinks.

Common Issues and Solutions

Sometimes the TOC does not appear. This is usually because the document was not opened in Word. The field code is only processed by Word. Open the file in Microsoft Word or LibreOffice.

Another issue is missing headings. Ensure all headings use the add_heading method. Manual paragraphs with bold text are not recognized.

If page numbers are wrong, update the TOC. Use the win32com method described above. This ensures accuracy.

Conclusion

Generating a table of contents in DOCX with Python is straightforward. Use python-docx to add headings and a TOC field. For automatic updates, use win32com. This saves time and reduces errors.

Follow the best practices we discussed. Structure your headings properly. Use templates for consistent styling. With these techniques, you can automate complex document generation.

Try the examples in this article. Customize them for your needs. Python makes DOCX automation easy and efficient.