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

Python-docx, how to set cell width in tables?

如何在表格中设置单元格宽度?,到目前为止我得到:

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中设置什么数字或单位,它的宽度都不会改变。

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

for cell in table.columns[0].cells:
    cell.width = Inches(0.5)
当您设置列宽时,

python-docx 执行您告诉它执行的操作。问题是 Word 会忽略它。 LibreOffice 等其他客户端遵守列宽设置。

.docx 文件采用 XML 格式(因此文件扩展名中有 'x' 后缀)。 tables 的 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

如果您的 table 合并了单元格,这会变得有点复杂,这实际上可能是 Word 忽略列宽的原因;它们在某些合并单元格情况下不明确。

docs of python_docx

allow_autofit 属性默认设置为 True,这意味着宽度设置不会生效,所以: table.allow_autofit = 假

对于 LibreOffice,我必须设置:

table.autofit = False 
table.allow_autofit = False

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

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

table = documento.add_table(行数=1, 列数=3, 样式="Table 网格") 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)

您可能还想使用 WD_ROW_HEIGHT_RULE,它可以绕过 table.

的自动调整
for row in table.rows:  
    row.height_rule = WD_ROW_HEIGHT_RULE.EXACTLY

这里是 doc 如果需要的话。

试试这个。此代码对我有用。

table2.cell(0,0).width = Inches(1.0)                                                
table2.cell(0,1).width = Inches(1.0)