• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / Python / Set Widths of Columns in Word Document Table with python-docx

Set Widths of Columns in Word Document Table with python-docx

March 16, 2021 Leave a Comment

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.

Other Articles You'll Also Like:

  • 1.  Change Python Turtle Shape Fill Color with fillcolor() Function
  • 2.  pandas Duplicated – Find Duplicate Rows in DataFrame or Series
  • 3.  How to Create Array from 1 to n in Python
  • 4.  Using Python to Sum Even Numbers in List
  • 5.  Shift Values in a List Using Python
  • 6.  How to Rotate a List in Python
  • 7.  How to Check If Value is in List Using Python
  • 8.  pandas percentile – Calculate Percentiles of Series or Columns in DataFrame
  • 9.  Python Check if Dictionary Value is Empty
  • 10.  Multiple Condition While Loops in Python

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy

x