简体   繁体   English

Python-docx - 使用一个命令合并表格的行或列(或列中的特定单元格子集)中的所有单元格

[英]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.我正在使用 python-docx 以编程方式在 word 文档中生成一个非常大且凌乱的表格。

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: MVP如下:

from docx import Document
doc = Document()

#adding table of details with 4 columns
tableOverview = doc.add_table(rows=1, cols=4)
tableOverview.style = 'Table Grid'

#add some text in a first cell of a row
row = tableOverview.row_cells(0)
row[0].text = "Job details"

#merge all 4 cells in a row into one
merge1 = row[0].merge(row[1]).merge(row[2]).merge(row[3])

However:然而:

  • This looks really ugly and un-pythonic to specify chain of merges这看起来真的很丑陋且不符合pythonic来指定合并链
  • 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!谢谢!

All you need provide to _Cell.merge() is the cell at the opposite diagonal of the rectangle you want to merge.您需要提供给_Cell.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:因此,例如,如果您想在 9 x 9 表格中合并左上角的 3 x 3 单元格区域,您可以使用:

table.cell(0, 0).merge(table.cell(2, 2))

or, more verbose but perhaps more instructive:或者,更冗长但也许更有启发性:

top_left = table.cell(0, 0)
bottom_right = table.cell(2, 2)
top_left.merge(bottom_right)

So all you need do is get a reference to any two diagonal corners.因此,您需要做的就是获取对任意两个对角角的引用。 Note that:注意:

bottom_right.merge(top_left)

works just as well as the other direction.和另一个方向一样有效。 For that matter:对于这个问题:

top_right = table.cell(0, 2)
bottom_left = table.cell(2, 0)
bottom_left.merge(top_right)

works just as well too.也同样有效。 Any two diagonal "corner" cells can be used to define a merged cell.任何两个对角线“角”单元格都可用于定义合并单元格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM