Search code examples
pythonpython-3.xpython-docx

How to add a table inside a header/footer with python and python-docx


I want to add a table of one row and three columns to my header. Any advice ?

I try with:

from docx import Document

document = Document()
section = document.sections[0]
header = section.header
table = header.add_table(rows=1, cols=3)  # method not yet implemented !

document.save('test.docx')

But obviously doesn't work


Solution

  • header.add_table() is implemented and should work. The implementation was recent (a couple months ago), so try upgrading your python-docx install:

    pip install -U python-docx
    

    Note that .add_table() takes three parameters, a row-count, a column-count, and a width, so something like this:

    from docx.shared import Inches
    
    table = header.add_table(1, 3, Inches(6))
    

    The documentation for that method is here:
    https://python-docx.readthedocs.io/en/latest/api/section.html#header-and-footer-objects