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')

No, what number or units do I set in col.width, its width does not change.

+4
source share
1 answer

Short answer: set the cell width separately.

for cell in table_columns[0].cells:
    cell.width = Inches(0.5)

python-docxdoes what you say when you set the column width. The problem is that Word ignores this. Other clients, such as LibreOffice, respect the column width setting.

A .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 ; .

+7

Source: https://habr.com/ru/post/1673329/


All Articles