Search code examples
python-docx

Why does this not set the widths?


Trying to set table column widths, but I can't.

According to threads I looked up here, something like this should set the cell width. Not sure what EMU are but I believe Mm(10) converts 10mm to EMU.

table.cell(0,0).width = 1097280

I made a very simple table, just 1 row. I thought this should set the column widths but all I get are 3 equal-width columns! Tried lots of different approaches.

EDIT: forgot to put the data

from docx import Document
from docx.shared import Pt, Mm, Cm, Inches
from docx.enum.table import WD_ALIGN_VERTICAL, WD_TABLE_ALIGNMENT


filename = "/home/pedro/myPython/docxFiles/example_table.docx"
doc = Document()
heading = 'Shiny new but awkward table" \n\n'
doc.add_heading(heading, 4)
table = doc.add_table(rows=1, cols=3)
table.alignment = WD_TABLE_ALIGNMENT.CENTER
table.autofit = False
table.allow_autofit = False
table.style = 'Table Grid'
headers = ["Name", "Age", "Occupation"]
widths = [15.9, 11.8, 26.7]
for col, col_data in enumerate(headers):
    print(col, col_data)
    table.cell(0,col).text = col_data
   
for col, width in enumerate(widths):
   print(col, width)
   table.cell(0, col).width = Mm(widths[col])
doc.save(filename)

Of course, I want to get the maximum string width in a column and set the column width to that or a maximum value, but for now even setting absolute values doesn't work for me.

What am I doing wrong? Maybe because I open it with Libre Office, not MS Word??

Any tips please?


Solution

  • When opening the document using MSWORD2013, and using SaveAs, the following screen appears:

    after saveas in msword2013

    When choosing OK, and opening the document in LibreOffice (version 7.6.2) it looks OK: document in LibreOffice 7.6.2

    The is already a bug at docx, see: No possible way to truly set Table Preferred Width