Last modified: Nov 08, 2025 By Alexander Williams
Automate Word Reports with Python docx
Manual Word document creation wastes time. Python-docx automates this process. It generates professional reports quickly.
This library creates and modifies .docx files. You can add text, tables, and images. All through Python code.
Install Python-docx
First, install the library. Use pip for installation. Run this command in your terminal.
pip install python-docx
Verify the installation. Import it in Python. No errors mean success.
import docx
print("Python-docx installed successfully!")
Create Your First Document
Start with a basic document. The Document class creates new files. Save with the save method.
from docx import Document
# Create a new document
doc = Document()
# Add a title
doc.add_heading('Automated Report', 0)
# Save the document
doc.save('first_report.docx')
This creates a Word file. It contains one heading. The file saves in your current directory.
Add Paragraphs and Text
Documents need content. Use add_paragraph for text. Add multiple paragraphs for structure.
# Add introductory paragraph
intro = doc.add_paragraph('This report was generated automatically using Python.')
intro.add_run(' This text is bold.').bold = True
intro.add_run(' This text is italic.').italic = True
# Add another paragraph
doc.add_paragraph('This is a second paragraph with normal text.')
doc.save('report_with_text.docx')
The output shows formatted text. Bold and italic styles appear. Each paragraph is separate.
For detailed paragraph formatting, see our Python-docx Paragraph Formatting Guide.
Create Headings and Structure
Headings organize documents. Use different levels. Level 0 is the title.
# Main title (Level 0)
doc.add_heading('Quarterly Sales Report', 0)
# Section heading (Level 1)
doc.add_heading('Executive Summary', 1)
# Subsection heading (Level 2)
doc.add_heading('Key Findings', 2)
doc.save('structured_report.docx')
This creates a document hierarchy. Readers can navigate easily. Structure improves readability.
Work with Tables
Tables present data clearly. Create them with add_table. Specify rows and columns.
# Add a table with 4 rows and 3 columns
table = doc.add_table(rows=4, cols=3)
# Set header row
headers = table.rows[0].cells
headers[0].text = 'Product'
headers[1].text = 'Q1 Sales'
headers[2].text = 'Q2 Sales'
# Add data rows
data = [
['Widget A', '1500', '1800'],
['Widget B', '2000', '2200'],
['Widget C', '1200', '1600']
]
for i, row_data in enumerate(data, 1):
row = table.rows[i].cells
row[0].text = row_data[0]
row[1].text = row_data[1]
row[2].text = row_data[2]
doc.save('report_with_table.docx')
The table displays sales data. Headers identify columns. Data fills the rows.
Learn advanced table techniques in our Python-docx Table Formatting Complete Guide.
Add Images to Reports
Images enhance visual appeal. Use add_picture to insert them. Control size with width and height.
# Add an image
doc.add_picture('chart.png', width=docx.shared.Inches(5))
# Add with specific height
doc.add_picture('logo.jpg', height=docx.shared.Cm(3))
doc.save('report_with_images.docx')
Images appear in the document. They resize according to specifications. Visual elements break up text.
For comprehensive image handling, visit our guide on Add Images to docx Using Python-docx.
Format Document Elements
Formatting improves appearance. Change fonts, colors, and alignment. Apply styles consistently.
from docx.shared import Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
# Create a formatted paragraph
paragraph = doc.add_paragraph()
paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
# Add formatted text
run = paragraph.add_run('Centered Bold Title')
run.bold = True
run.font.size = Pt(16)
run.font.color.rgb = docx.shared.RGBColor(0, 0, 128) # Navy blue
doc.save('formatted_report.docx')
The text appears centered and bold. Blue color and larger size stand out. Professional formatting impresses readers.
Real-World Example: Sales Report
Combine all elements. Create a complete sales report. This demonstrates practical automation.
from datetime import datetime
from docx import Document
from docx.shared import Inches
# Create document
doc = Document()
# Title with date
current_date = datetime.now().strftime("%B %d, %Y")
doc.add_heading(f'Sales Report - {current_date}', 0)
# Executive summary
doc.add_heading('Executive Summary', 1)
doc.add_paragraph('This report summarizes quarterly sales performance across all product lines.')
# Sales data table
doc.add_heading('Sales Data', 1)
table = doc.add_table(rows=5, cols=4)
table.style = 'Light Grid Accent 1'
# Table headers
headers = ['Region', 'Q1 Sales', 'Q2 Sales', 'Growth']
header_cells = table.rows[0].cells
for i, header in enumerate(headers):
header_cells[i].text = header
# Table data
data = [
['North', '$150,000', '$180,000', '20%'],
['South', '$200,000', '$220,000', '10%'],
['East', '$175,000', '$190,000', '8.6%'],
['West', '$160,000', '$185,000', '15.6%']
]
for row_idx, row_data in enumerate(data, 1):
row_cells = table.rows[row_idx].cells
for col_idx, cell_data in enumerate(row_data):
row_cells[col_idx].text = cell_data
# Conclusion
doc.add_heading('Conclusion', 1)
doc.add_paragraph('Overall sales show positive growth across all regions. The North region demonstrated the strongest performance.')
# Save final report
doc.save('complete_sales_report.docx')
print("Sales report generated successfully!")
This creates a professional sales report. It includes a title, summary, data table, and conclusion. All elements work together.
Advanced Features
Python-docx offers more capabilities. Add page breaks, sections, and headers. Customize every aspect.
from docx.enum.section import WD_SECTION
# Add section break
doc.add_section(WD_SECTION.NEW_PAGE)
# Add header
section = doc.sections[0]
header = section.header
header_para = header.paragraphs[0]
header_para.text = "Confidential - Company Internal Use Only"
doc.save('advanced_report.docx')
The document now has multiple sections. Headers appear on each page. Page breaks control content flow.
Best Practices
Follow these guidelines for success. They ensure reliable and maintainable code.
Use consistent naming conventions. Name documents and variables clearly. This improves code readability.
Handle exceptions properly. Check for file permissions and paths. Prevent crashes during execution.
Separate data from presentation. Keep data in variables or files. The code should focus on formatting.
Test with different data sizes. Ensure your code handles various scenarios. Small and large datasets should work.
Conclusion
Python-docx transforms Word document creation. It automates repetitive reporting tasks. This saves time and reduces errors.
You can generate complex documents programmatically. Add text, tables, images, and formatting. All with simple Python code.
Start with basic documents. Gradually incorporate advanced features. Your reports will become more sophisticated.
Automation improves consistency and efficiency. Focus on analysis rather than manual formatting. Python-docx makes this possible.
Begin your automation journey today. The library is powerful yet accessible. Even beginners can create impressive results quickly.