Python Docx Table 列宽

Python Docx Table Column width

我知道我遗漏了一些简单的东西,但它并没有深入。我知道我必须设置每个单元格的宽度。

我想在 Word docx 中构建一个 table,其中第一列为 1.2 英寸,第二列为 5.3 英寸。当我尝试以下操作时,第一列是 0.63 英寸,第二列是 1.72 英寸。我为宽度尺寸设置什么似乎并不重要。我在第一列上尝试了 3.0,它仍然显示为 0.63 英寸。我在这里错过了什么?

import docx

doc = docx.Document()
doc.add_heading('Name: ', level=1)

table = doc.add_table(rows=4, cols=2)
table.cell(0,0).width = 1.2
table.cell(1,0).width = 1.2
table.cell(2,0).width = 1.2
table.cell(3,0).width = 1.2
table.cell(0,1).width = 5.3
table.cell(1,1).width = 5.3
table.cell(2,1).width = 5.3
table.cell(3,1).width = 5.3

table.cell(0,0).text = 'Time Zone'
table.cell(1,0).text = 'Link'
table.cell(1,1).text = 'https://www.google.com/'
table.cell(2,0).text = 'Website'
table.cell(3,0).text = 'Facebook'

doc.save('test.docx')

单元格对象的宽度以 EMU 为单位而不是以英寸为单位:https://python-docx.readthedocs.io/en/latest/api/table.html#docx.table._Cell.width

一英寸有 914400 个 EMU,因此请按如下方式转换您的代码,它应该可以工作:

table.cell(0,0).width = 1097280     # 1.2 * 914400
table.cell(1,0).width = 1097280
table.cell(2,0).width = 1097280
table.cell(3,0).width = 1097280
table.cell(0,1).width = 4846320    # 5.3 * 914400 
table.cell(1,1).width = 4846320
table.cell(2,1).width = 4846320
table.cell(3,1).width = 4846320

您可以这样使用英寸:

table.cell(0,0).width = Inches(1.0)