Skip to content
Advertisement

Python-docx – merge ALL cells in a row or column of a table (or a specific subset of cells in a column) with one command

I am using python-docx to programmatically generate a very large and messy table inside of word document.

How, as part of beautification process I need to merge together all cells in specific rows or columns.

When I know how many cells are there in a row or column in advance merge is trivial. MVP below:

JavaScript

However:

  • This looks really ugly and un-pythonic to specify chain of merges
  • It gets tricky if I don’t know in advance how many cells are there in a row (or in a column). This becomes a problem as I am generating this tables based on inputs hence number of cells per row and column is dynamic – so I can’t hardcode such merge chain

Quick check of documentation didn’t yield any good examples, it is always the case that there are just two cells being merged at a time. Is there some reasonable way to merge together a whole list of cells?

Thanks!

Advertisement

Answer

All you need provide to _Cell.merge() is the cell at the opposite diagonal of the rectangle you want to merge.

So, for example, if you wanted to merge the top-left 3 x 3 cell area in a 9 x 9 table, you could use:

JavaScript

or, more verbose but perhaps more instructive:

JavaScript

So all you need do is get a reference to any two diagonal corners. Note that:

JavaScript

works just as well as the other direction. For that matter:

JavaScript

works just as well too. Any two diagonal “corner” cells can be used to define a merged cell.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement