Python-docx, how to set cell width in tables?
Solution 1
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.
Solution 2
allow_autofit attribute was default set to be True, which mean the width set will not take effect, so: table.allow_autofit = False
Solution 3
For LibreOffice I had to set:
table.autofit = False
table.allow_autofit = False
Next, set given column and cell width
table.columns[0].width = Inches(1.0)
table.rows[0].cells[0].width = Inches(1.0)
Solution 4
table = documento.add_table(rows=1, cols=3, style="Table Grid") 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)
Related videos on Youtube
girdeux
Updated on July 09, 2022Comments
-
girdeux almost 2 years
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.
-
altendky about 7 yearsCould skip the indexes with
for cell, width in zip(row.cells, (Inches(1), Inches(2), Inches(1.5))): cell.width = width
-
Garrett almost 4 yearsFor LibreOffice, I also had to change the column widths (
for idx, col in enumerate(table.columns): col.width = widths[idx]
) -
Satya Dev Yadav over 3 yearsfor cell in table_columns[0].cells: cell.width = Inches(0.5) Not working, not set the width!
-
Rob Irwin almost 3 yearsThe first code snippet has a typo. Should be:
for cell in table.columns[0].cells
-
scanny almost 3 yearsI fixed the typo.
-
peter almost 3 years@scanny, is it possible to use Percent instead of Inches or Cm instead?