3

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?

3
  • 1
    I don't know in Python, but in C# you need to give the TableCell a GridSpan instance. EDIT: looking at the source code, it doesn't seem like you can do this with python-docx. Commented Mar 28, 2013 at 21:36
  • Thanks for the input. I'm working out how to do this using lxml directly, should be able to add an answer soon. Commented Mar 29, 2013 at 14:39
  • Haven't had a chance to work on it lately (other priorities). I'll make an update here if I manage to chip away at it. Commented Jun 10, 2013 at 8:24

1 Answer 1

4

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.
Sign up to request clarification or add additional context in comments.

4 Comments

Following discussions with the python-docx maintainer, another, more complete implementation was made. It's being hosted here: github.com/Apteryks/python-docx/tree/cell-merge_feature. Any table cell now has a 'merge' method which takes another table cell as argument. It can merge both horizontally, vertically, or both.
Sorry it took so long for this answer to be accepted.
Github link is no longer valid.
@LMc: I must have deleted that branch since the feature got merged in. That is good news, but the API differs a bit, since it can merge in both directions. Suppose that you have a 3x3 table and would like to merge the first row, you could do: my_table.cell(0, 0).merge(my_table.cell(0, 2)) if I remember correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.