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')
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 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.
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
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.
如何在表格中设置单元格宽度?,到目前为止,我得到了:
from docx import Document
from docx.shared导入Cm,英寸
document = Document()
table = document.add_table(rows = 2,cols = 2)
table.style ='TableGrid'#所有单元格中的单行
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中设置的数字或单位如何,其宽度都不会改变。
简短答案:分别设置单元格宽度。
对于table_columns [0] .cells中的单元格:
cell.width =英寸(0.5)
python- docx 会执行设置列宽时告诉它的操作。问题在于Word会忽略它。其他客户端(例如LibreOffice)也尊重列宽设置。
A .docx 文件为XML格式(因此文件扩展名中的 x后缀)。表的XML词汇表有一个列宽位置和一个单元格宽度位置。谁在关注这个细节时有些烦恼。一个共同的标准是,每个人都遵守在单个单元格级别设置的显式宽度。这对我来说意义不大,但这就是使它起作用的必要条件。在您的程序中有一个照顾细节的函数可能很有意义:
def set_col_widths(table):
widths =(Inches(1),Inches(2),Inches(1.5))
用于table.rows中的行:
for idx,枚举中的宽度(widths):
行.cells [idx] .width = width
如果您的表合并了单元格,这会变得更加复杂,这实际上可能是Word忽略列宽的原因;在某些合并单元格情况下它们是不明确的