Lecture

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 load CSV 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).

Adding a Table
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).

Adding Text to a Cell
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'.

Setting Table Style
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.

Adding 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.

Adding a New Column
from docx.shared import Inches table.add_column(Inches(1))

cell.text

This property is used to set or retrieve text in a cell.

Adding Text to 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.

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

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

Run
Generate

Execution Result

Result

The document is empty.

Try running the code.