Search code examples
pythonopenxmlpython-docx

Cell spanning multiple columns in table using python-docx


I'm trying to create a table that looks like this, using the python-docx module.

Example of the table I want to create

Working from the example code for creating a table in example-makedocument.py and reading through the code in docx.py, I thought something similar to this would work:

tbl_rows = [ ['A1'], 
       ['B1', 'B2' ],
       ['C1', 'C2' ] ]
tbl_colw = [ [100],
       [25, 75],
       [25, 75] ]
tbl_cwunit = 'pct'

body.append(table(tbl_rows, colw=tbl_colw, cwunit=tbl_cwunit))

however this corrupts the docx document, and when Word recovers the document the table is shown as this:

Actual table created

How can I get a row to properly span multiple columns using python-docx?


Solution

  • I added a merge_cells() function to the row class of python-docx, that can merge any cells on a single row. I'm hoping it will get included in python-docx. In the meantime, you can grab it from my github "merge_cells_feature" python-docx branch.

    I'm copying the example I wrote on the pull request here for reference:

    from docx import Document
    
    doc = Document()
    table = doc.add_table(6,6)
    header_row = table.rows[0]
    header_row.merge_cells()
    
    # args can also be passed to merge_cells(mergeStart, mergeStop) in order to 
    # implement any kind of merge on the same row, such as:
    table.rows[1].merge_cells(0,3)  # This will merge the cells indexed from 0 to 2.