Python-docx,如何在表格中设置单元格宽度? [英] Python-docx, how to set cell width in tables?
问题描述
如何在表格中设置单元格宽度?到目前为止,我知道了:
How to set cell width in tables?, so far I got:
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中设置的数字或单位是多少,其宽度都不会改变.
No mater what number or units I set in col.width, its width does not change.
推荐答案
简短答案:分别设置像元宽度.
Short answer: set cell width individually.
for cell in table_columns[0].cells:
cell.width = Inches(0.5)
设置列宽时,
python-docx
会执行告诉您的操作.问题在于Word会忽略它.其他客户端,例如LibreOffice,都遵循列宽设置.
python-docx
does what you tell it to do when you set column width. The problem is that Word ignores it. Other clients, like LibreOffice, respect the column width setting.
.docx
文件为XML格式(因此文件扩展名中带有'x'后缀).表的XML词汇表有一个列宽位置和一个单元格宽度位置.谁在关注这个细节时有些烦恼.一个共同的标准是,每个人都遵守在单个单元格级别设置的显式宽度.对我而言,这没有多大意义,但这是使其工作所需的.在您的程序中拥有一个照顾细节的功能可能很有意义:
A .docx
file is in XML format (hence the 'x' suffix in the file extension). The XML vocabulary for tables has a place for column width and a place for cell width. Who pays attention to what is a bit vexed when it comes to this detail. The one common denominator is that everyone respects explicit widths set at the individual cell level. It doesn't make a lot of sense to me, but this is what it takes to make it work. It might make sense to have a function in your program that takes care of the details:
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忽略列宽的原因.在某些合并单元情况下它们是不明确的.
This gets a bit more complicated if your table has merged cells, which could actually be the reason Word ignores column widths; they're ambiguous in certain merged-cell situations.
这篇关于Python-docx,如何在表格中设置单元格宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!