Dec-02-2023, 11:36 AM
(This post was last modified: Dec-02-2023, 11:37 AM by Pedroski55.)
Hola Pepe!
This was tricky. Especially because, if you open this .docx file in Libre Office, the table has 3 equal-width columns! Libre Office seems to ignore the column size settings. For a while, I was going crazy!
But if you open it in MS Word the columns have the correct widths!
I just made a 1 row table to see if the column widths are set correctly.
import the imports, then just run myApp() Of course, you need to set your path for filename!
I had to start Windows and open the file with MS Word, then it displays correctly.
Now you just need to set the column widths to the largest string length, as you were doing.
However, if a string is too long, your table will run off the page. So you better set a maximum column width, I think.
This was tricky. Especially because, if you open this .docx file in Libre Office, the table has 3 equal-width columns! Libre Office seems to ignore the column size settings. For a while, I was going crazy!
But if you open it in MS Word the columns have the correct widths!
I just made a 1 row table to see if the column widths are set correctly.
import the imports, then just run myApp() Of course, you need to set your path for filename!
from docx import Document from docx.shared import Pt, Mm, Cm, Inches from docx.enum.table import WD_ALIGN_VERTICAL, WD_TABLE_ALIGNMENT def myApp(): 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)I think you need these 2:
Quote:table.autofit = False
table.allow_autofit = False
I had to start Windows and open the file with MS Word, then it displays correctly.
Now you just need to set the column widths to the largest string length, as you were doing.
However, if a string is too long, your table will run off the page. So you better set a maximum column width, I think.