使用python-docx跨表格中的多个列的单元格 [英] Cell spanning multiple columns in table using python-docx
问题描述
我正在尝试使用 python-docx 模块.
从在example-makedocument.py中创建表的示例代码开始,并通读docx.py中的代码,我认为类似的事情会起作用:
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))
但是这会损坏docx文档,而当Word恢复文档时,该表将显示为:
however this corrupts the docx document, and when Word recovers the document the table is shown as this:
如何使用python-docx获得一行以正确跨越多列?
How can I get a row to properly span multiple columns using python-docx?
推荐答案
我向python-docx的行类添加了merge_cells()函数,该函数可以合并一行中的任何单元格.我希望它将包含在python-docx中.同时,您可以从我的github"merge_cells_feature" python-docx分支中获取它.
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.
这篇关于使用python-docx跨表格中的多个列的单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!