How to Create Tables with Python Code
For simple tables, it’s faster to manually create them using the Table feature in a word processor.
However, if you need to insert large datasets into tables or automate repetitive table creation, it’s better to use the python-docx
library.
In this lesson, we’ll explore the main methods for adding tables to Word documents using python-docx.
Note: For convenience, the data visualized as tables is defined as Python lists. In practice, it is common to use the
pandas
library to loadCSV
files from URLs.
add_table()
This method adds a new table to the document.
It is used as document.add_table(rows, cols)
where rows
specifies the number of rows (horizontal) and cols
specifies the number of columns (vertical).
from docx import Document doc = Document() table = doc.add_table(rows=3, cols=3)
table.cell(row, col)
This method accesses a specific cell to set or retrieve its value.
It is used as table.cell(row, col)
where row
is the row number (starting at 0) and col
is the column number (starting at 0).
cell = table.cell(0, 0) # First row, first column cell.text = "Hello, World!"
table.style
This property sets 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=3) table.style = 'Table Grid' # Use a predefined style in Word
table.add_row()
This method adds a new row (horizontal line) to the table.
Use table.add_row()
to add a new row.
row = table.add_row() row.cells[0].text = "New Cell"
table.add_column()
This method adds a new column (vertical line) to the table.
Use table.add_column(width)
to add a new column with a specified width.
from docx.shared import Inches table.add_column(Inches(1))
cell.text
This property is used to set or retrieve text in a cell.
cell = table.cell(1, 1) cell.text = "Sample Text"
cell.merge(other_cell)
This method merges cells.
The following code demonstrates merging two cells in the first row.
a = table.cell(0, 0) b = table.cell(0, 1) a.merge(b) # Merge two cells in the first row
What is the method to add a horizontal row to a table in python-docx?
add_table()
table.cell(row, col)
table.add_row()
table.add_column()
Lecture
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result
The document is empty.
Try running the code.