Skip to main content
Practice

How to Create Tables with Python Code

When creating a simple table, using the Table feature of a word processing program is convenient.

However, when you need to insert large amounts of data into a table or automate repetitive table creation, it is best to use the python-docx library.

In this lesson, we will learn how to add tables to a Word file using python-docx.

Note: The data visualized in the tables is defined as Python lists for ease of understanding. However, it is common to use the pandas library to read CSV files from file paths or URLs in practice.


add_table()

This method is used to add a table to a document.

You use it like document.add_table(rows, cols) where

  • rows: number of rows

  • cols: number of columns

are specified.

Add a Table
from docx import Document

doc = Document()

# Create a table with 3 rows and 2 columns
table = doc.add_table(rows=3, cols=2)

table.cell(row, col)

Access a specific cell to set or retrieve its value.

Use it like table.cell(row, col), where row is the row number (starting from 0) and col is the column number (starting from 0).

Add Text to a Cell
# Cell at the first row, first column
cell = table.cell(0, 0)

cell.text

Set or retrieve the text in a cell.

Add Text to a Cell
# Cell at the first row, first column
cell = table.cell(0, 0)

# Add text to the specified cell
cell.text = "Hello"

table.style

Set the style of the table.

To create a table with borders, use table.style = 'Table Grid'.

Set Table Style
doc = Document()

table = doc.add_table(rows=3, cols=2)

# Create a table with solid borders
table.style = 'Table Grid'

table.add_row()

This method adds a new row to the table.

Add a new row with table.add_row().

Add a New Row
row = table.add_row()

row.cells[0].text = "New Cell"

table.add_column()

This method adds a new column to the table.

Add a new column with table.add_column(width) where you specify the width.

You must specify the width when adding a column.

Add a New Column
from docx.shared import Inches

table.add_column(Inches(1))

cell.merge(other_cell)

This method merges cells.

The code below is an example of merging the first two cells in the first row.

Merge Cells
a = table.cell(0, 0)
b = table.cell(0, 1)
a.merge(b) # Merge the first two cells in the first row

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.