Python-docx,如何在表格中设置单元格宽度?

36

如何设置表格中单元格的宽度?到目前为止,我得到了以下内容:

from docx import Document
from docx.shared import Cm, Inches

document = Document()
table = document.add_table(rows=2, cols=2)
table.style = 'TableGrid' #single lines in all cells
table.autofit = False

col = table.columns[0] 
col.width=Inches(0.5)
#col.width=Cm(1.0)
#col.width=360000 #=1cm

document.save('test.docx')
无论我设置什么数字或单位,col.width 的宽度都不会改变。
6个回答

54

简短回答:单独设置单元格宽度。

for cell in table.columns[0].cells:
    cell.width = Inches(0.5)

python-docx 在设置列宽时会按照你的要求去做,但问题是Word会忽略它。而其他一些客户端比如LibreOffice会尊重列宽的设置。

.docx 文件是XML格式的(因此文件扩展名带有“x”后缀)。表格的XML词汇有一个地方用于列宽和一个地方用于单元格宽度。当涉及到这个细节时,关注什么有点棘手。唯一的共同点是每个人都尊重在单个单元格级别上设置的显式宽度。这对我来说并不太有意义,但这就是使它起作用所需要的。也许在你的程序中有一个函数来处理这些细节会更有意义:

def set_col_widths(table):
    widths = (Inches(1), Inches(2), Inches(1.5))
    for row in table.rows:
        for idx, width in enumerate(widths):
            row.cells[idx].width = width

如果您的表格具有合并单元格,情况会变得稍微复杂一些,这可能是Word忽略列宽的原因;在某些合并单元格的情况下,它们是含糊不清的。


可以使用以下代码跳过索引:for cell, width in zip(row.cells, (Inches(1), Inches(2), Inches(1.5))): cell.width = width - altendky
1
对于LibreOffice,我还需要更改列宽度 (for idx, col in enumerate(table.columns): col.width = widths[idx])。 - Garrett
对于表格列中的单元格: cell.width = Inches(0.5) 无效,未设置宽度! - Satya Dev Yadav
第一段代码片段有一个错别字。应该是:for cell in table.columns[0].cells - Rob Irwin
我修正了打字错误。 - scanny
@scanny,可以使用百分比代替英寸或厘米吗? - peter

9

对于LibreOffice,我需要设置:

table.autofit = False 
table.allow_autofit = False

接下来,设置给定列和单元格宽度。

table.columns[0].width = Inches(1.0)
table.rows[0].cells[0].width = Inches(1.0)

3

Python_docx 文档

allow_autofit 属性默认为 True,这意味着设置的宽度不会生效,因此:table.allow_autofit = False


1
尝试这个。这段代码对我有效。
table2.cell(0,0).width = Inches(1.0)                                                
table2.cell(0,1).width = Inches(1.0)

1

table = documento.add_table(rows=1, cols=3, style="表格网格") table.alignment = WD_ALIGN_PARAGRAPH.CENTER

        table.allow_autofit = True
        table.columns[0].width = Cm(3.5)
        table.columns[1].width = Cm(7.5)
        table.columns[2].width = Cm(5.5)

0
你可能想要使用WD_ROW_HEIGHT_RULE,它可以绕过表格中的自适应调整。
for row in table.rows:  
    row.height_rule = WD_ROW_HEIGHT_RULE.EXACTLY

如果需要,这里是文档


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接