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 readCSV
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.
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).
# Cell at the first row, first column
cell = table.cell(0, 0)
cell.text
Set or retrieve the text in 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'
.
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()
.
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.
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.
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.