Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Docx Table Column width

I know I'm missing something simple, but it's not sinking in. I know I have to set the width on each individual cell.

I want to build a table in a Word docx where the first column is 1.2 inches and the second column is 5.3 inches. When I try the following, the first column is 0.63 inches and the second column is 1.72 inches. It doesn't seem to matter what I put for the width sizes. I've tried a 3.0 on the first column and it still shows as 0.63 inches. What am I missing here?

import docx

doc = docx.Document()
doc.add_heading('Name: ', level=1)

table = doc.add_table(rows=4, cols=2)
table.cell(0,0).width = 1.2
table.cell(1,0).width = 1.2
table.cell(2,0).width = 1.2
table.cell(3,0).width = 1.2
table.cell(0,1).width = 5.3
table.cell(1,1).width = 5.3
table.cell(2,1).width = 5.3
table.cell(3,1).width = 5.3

table.cell(0,0).text = 'Time Zone'
table.cell(1,0).text = 'Link'
table.cell(1,1).text = 'https://www.google.com/'
table.cell(2,0).text = 'Website'
table.cell(3,0).text = 'Facebook'

doc.save('test.docx')
like image 328
ScottC Avatar asked Dec 19 '22 07:12

ScottC


2 Answers

You can use inches this way:

table.cell(0,0).width = Inches(1.0)
like image 76
Ryan Skene Avatar answered Dec 20 '22 22:12

Ryan Skene


Width of the cell objects is in EMUs and not in inches: https://python-docx.readthedocs.io/en/latest/api/table.html#docx.table._Cell.width

One inch has 914400 EMUs so convert your code like below and it should work:

table.cell(0,0).width = 1097280     # 1.2 * 914400
table.cell(1,0).width = 1097280
table.cell(2,0).width = 1097280
table.cell(3,0).width = 1097280
table.cell(0,1).width = 4846320    # 5.3 * 914400 
table.cell(1,1).width = 4846320
table.cell(2,1).width = 4846320
table.cell(3,1).width = 4846320
like image 26
yeniv Avatar answered Dec 20 '22 22:12

yeniv