Creating Word documents using the Python Docx package is very powerful and allows us to present our data and findings in an automated way.
Many times, we are working with data and want to output this data into a table.
Outputting data to a table in a Word Document in Python is not difficult, but formatting the table and in particular, setting the widths of the columns can be a little tedious.
Set Widths of Columns in Word Document Table with Python Docx
When working with tables using Python Docx, the thing to understand is that when formatting the table, we need to apply these formats to every cell.
In this case, we need to set the width of every cell in our table.
To do this, you can use the following code to set the widths of your table columns.
import pandas as pd
import docx
from docx.shared import Cm, Inches
data = pd.read_excel("some_file_path_with_data.xlsx")
doc = docx.Document()
widths = [Inches(1), Inches(0.5), Inches(0.75)]
table = doc.add_table(rows=data.shape[0], cols=data.shape[1])
table_cells = table._cells
for i in range(data.shape[0]):
for j, cell in enumerate(table.rows[i].cells):
cell.text = str(data.values[i][j])
cell.width = widths[j]
doc.save("output_path.docx")
Something that you should note above is that you will want to make sure that the columns of your data, the size of your table, and the size of your widths array all match up.
Another example is if you have a heading row.
There, you will want to set the widths of these columns as well, as done below:
import pandas as pd
import docx
from docx.shared import Cm, Inches
data = pd.read_excel("some_file_path_with_data.xlsx")
doc = docx.Document()
widths = [Inches(1), Inches(0.5), Inches(0.75)]
table = doc.add_table(rows=data.shape[0], cols=data.shape[1])
column_names = ["Column Name 1", "Column Name 2", "Column Name 3"]
heading_cells = table.rows[0].cells
for j in range(len(header)):
heading_cells[j].text = column_names[j]
heading_cells[j].width = widths[j]
table_cells = table._cells
for i in range(1, data.shape[0]):
for j, cell in enumerate(table.rows[i].cells):
cell.text = str(data.values[i][j])
cell.width = widths[j]
doc.save("output_path.docx")
Hopefully this article has been helpful for you in your pursuit of creating automated Word documents using Python Docx. If you have any questions, feel free to leave a comment. Thank you for reading.