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

问题描述 投票:0回答:7

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

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

python ms-word python-docx column-width
7个回答
52
投票

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

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 忽略列宽的原因;它们在某些合并单元格的情况下是不明确的。


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
投票

table = documento.add_table(rows=1, cols=3, style="表格网格") 表.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)

1
投票

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

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

0
投票

您可能还想使用WD_ROW_HEIGHT_RULE,它可以绕过表中的自动调整。

for row in table.rows:  
    row.height_rule = WD_ROW_HEIGHT_RULE.EXACTLY

如果需要的话,这是doc


0
投票

此方法在使用 LibreOffice 时不起作用(至少在 5.3.6.1 版本上)。

与上面提到的相反,为了让它工作,我必须设置列宽,因为当您单独设置每个单元格时,LibreOffice 不尊重。

table.columns[0].width = Inches(0.5)
© www.soinside.com 2019 - 2024. All rights reserved.