Last modified: Nov 08, 2025 By Alexander Williams

Python-docx Table Formatting Complete Guide

Python-docx makes Word document automation easy. This guide covers table creation and formatting. You will learn to build professional tables.

Tables organize data effectively in documents. Python-docx provides powerful table handling. You can control every aspect of table appearance.

Getting Started with Python-docx

First, ensure python-docx is installed. Use pip for installation. Check our Install Python-docx for Word Documents guide if needed.


# Install python-docx
pip install python-docx

Import the module in your script. Create a document object. This serves as your working canvas.


from docx import Document

# Create a new document
doc = Document()

Creating Basic Tables

Tables start with rows and columns. Use the add_table() method. Specify rows and columns as parameters.


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

# Access cells and add data
table.cell(0, 0).text = "Name"
table.cell(0, 1).text = "Age"
table.cell(0, 2).text = "City"
table.cell(0, 3).text = "Score"

# Add data rows
table.cell(1, 0).text = "John"
table.cell(1, 1).text = "25"
table.cell(1, 2).text = "New York"
table.cell(1, 3).text = "85"

table.cell(2, 0).text = "Sarah"
table.cell(2, 1).text = "30"
table.cell(2, 2).text = "London"
table.cell(2, 3).text = "92"

This creates a simple data table. The first row acts as headers. Subsequent rows contain actual data.

Table Style Formatting

Python-docx offers built-in table styles. Apply them using the style property. This quickly enhances table appearance.


# Apply a built-in table style
table.style = 'Light Grid Accent 1'

# Save the document
doc.save('formatted_table.docx')

Built-in styles include shading and borders. They provide professional looks instantly. Experiment with different style names.

Custom Border Formatting

For precise control, customize borders manually. Access table borders through the border property. Set individual border sides.


from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.shared import Pt

# Set table alignment
table.alignment = WD_TABLE_ALIGNMENT.CENTER

# Format table borders
border_style = table.style.paragraph_format.border
border_style.bottom.color = "000000"
border_style.bottom.space = Pt(1)
border_style.bottom.size = Pt(2)

You can control border color, size, and spacing. This enables custom design matching your brand.

Cell Formatting and Merging

Format individual cells for emphasis. Merge cells for complex layouts. Use merge() for spanning multiple cells.


# Merge cells in the first row for a title
title_cell = table.cell(0, 0)
table.cell(0, 1).merge(title_cell)
table.cell(0, 2).merge(title_cell)
table.cell(0, 3).merge(title_cell)
title_cell.text = "Employee Data Summary"

# Format the title cell
title_cell.paragraphs[0].alignment = 1  # Center alignment
run = title_cell.paragraphs[0].runs[0]
run.bold = True
run.font.size = Pt(14)

Merged cells create header sections. They help organize complex data hierarchies.

Row and Column Formatting

Format entire rows or columns consistently. Control height, alignment, and background colors. This improves readability.


from docx.shared import Inches

# Set row height
table.rows[0].height = Inches(0.5)

# Format header row
for cell in table.rows[0].cells:
    cell.paragraphs[0].alignment = 1  # Center
    cell.paragraphs[0].runs[0].bold = True
    # Set background color (shading)
    cell._element.get_or_add_tcPr().append(parse_xml(r''.format(nsdecls('w'))))

Header rows benefit from distinct formatting. This separates them from data rows clearly.

Advanced Cell Formatting

Go beyond basic text formatting. Control paragraph alignment within cells. Adjust vertical alignment too.


from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_ALIGN_VERTICAL

# Access a specific cell
sample_cell = table.cell(1, 1)

# Horizontal alignment
sample_cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER

# Vertical alignment
sample_cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER

# Cell margins
sample_cell.margin_top = Inches(0.1)
sample_cell.margin_bottom = Inches(0.1)
sample_cell.margin_left = Inches(0.1)
sample_cell.margin_right = Inches(0.1)

Proper alignment enhances data presentation. It makes tables more professional and readable.

Working with Table Width

Control table width for optimal layout. Set preferred width as absolute or percentage. This ensures consistent appearance.


from docx.enum.table import WD_TABLE_ALIGNMENT

# Set table width to 6 inches
table.autofit = False
table.width = Inches(6)

# Or set relative width (percentage of page width)
# table.width = doc.sections[0].page_width * 0.8  # 80% of page width

# Column width adjustment
table.columns[0].width = Inches(1.5)
table.columns[1].width = Inches(1.0)
table.columns[2].width = Inches(2.0)
table.columns[3].width = Inches(1.5)

Width control prevents awkward table layouts. It ensures proper fitting on the page.

Combining Tables with Other Elements

Tables work well with other document elements. Add paragraphs before or after tables. Include images for comprehensive reports.

Check our Add Images to docx Using Python-docx guide for image integration. Combine tables with formatted text for professional documents.

For text formatting around tables, see our Python-docx Paragraph Formatting Guide. This completes your document creation skills.

Complete Table Example

Here is a full working example. It demonstrates multiple formatting techniques together.


from docx import Document
from docx.shared import Inches, Pt
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICAL
from docx.enum.text import WD_ALIGN_PARAGRAPH

# Create document and table
doc = Document()
table = doc.add_table(rows=4, cols=3)
table.alignment = WD_TABLE_ALIGNMENT.CENTER

# Set column headers
headers = ['Product', 'Quantity', 'Price']
for i, header in enumerate(headers):
    cell = table.cell(0, i)
    cell.text = header
    cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
    cell.paragraphs[0].runs[0].bold = True

# Add sample data
data = [
    ['Laptop', '15', '$1200'],
    ['Mouse', '45', '$25'],
    ['Keyboard', '30', '$75']
]

for row_idx, row_data in enumerate(data, 1):
    for col_idx, cell_data in enumerate(row_data):
        cell = table.cell(row_idx, col_idx)
        cell.text = cell_data
        cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER

# Set column widths
table.columns[0].width = Inches(2.0)
table.columns[1].width = Inches(1.5)
table.columns[2].width = Inches(1.5)

doc.save('complete_table_example.docx')
print("Table created successfully!")

Table created successfully!

Conclusion

Python-docx provides comprehensive table formatting capabilities. You can create simple to complex tables. Formatting options cover all visual aspects.

Mastering table formatting enhances your document automation skills. Combine tables with other elements for professional reports. Practice with different scenarios.

Start with basic tables. Gradually incorporate advanced formatting. Your Word documents will impress with well-formatted tables.