Introduction
Batch generation of contracts, analytical reports and project specification files is one of the most frequent demands for office automation development. Manual copy-and-paste leads to low productivity and inconsistent document formatting standards across batches of Word files.
This practical tutorial focuses on how to generate Word documents with Python via the free edition of Spire.Doc for Python. We deliver complete runnable code examples, ranging from blank DOCX initialization to embedding formatted data tables, local images, headers, footers and full automated project reports.
1. Set Up
1.1 Overview
Free Spire.Doc for Python is a standalone open-free Python library built for full-cycle Word document processing. It supports creating, reading, modifying and converting legacy .doc and modern .docx formats entirely without MS Word.
1.2 Install via PIP Command
Execute the below pip command inside your Python terminal to install the DOCX generation dependency:
pip install Spire.Doc.Free
1.3 Import Core Modules
Add these import statements at the top of every Python script for generating Word documents with Free Spire.Doc:
from spire.doc import *
from spire.doc.common import *
2. Basic: Create DOCX File From Scratch in Python
All Word files built with this Python SDK follow a fixed nested object structure:
Document β Section β Paragraph β TextRange
-
Document: Top root instance representing a complete Word DOCX file -
Section: Independent page layout container to customize margins, headers, footers and page orientation separately -
Paragraph: Core block container for all visible text content -
TextRange: Fragment for continuous formatted text inside a single paragraph
2.1 Build Basic Word Document With Built-in Styles
Below sample code creates a complete formatted DOCX file with title, H1 heading and normal body text, a foundational operation when you generate Word documents with Python:
# Initialize blank document instance
doc = Document()
# Create new document section
section = doc.AddSection()
# Customize page margin (unit: point)
section.PageSetup.Margins.Top = 60
section.PageSetup.Margins.Bottom = 60
section.PageSetup.Margins.Left = 70
section.PageSetup.Margins.Right = 70
# Add formatted title with built-in Title style
title = section.AddParagraph()
title.AppendText("2026 Annual Technical Report")
title.ApplyStyle(BuiltinStyle.Title)
# Add H1 heading
heading1 = section.AddParagraph()
heading1.AppendText("I. Project Overview")
heading1.ApplyStyle(BuiltinStyle.Heading1)
# Add normal body text
para = section.AddParagraph()
para.AppendText("This report summarizes the work achievements of the technical team in 2026 in core product development, performance optimization, and user experience enhancement.")
para.ApplyStyle(BuiltinStyle.Normal)
# Export DOCX and release system resource
doc.SaveToFile("demo.docx")
doc.Dispose()
2.2 Define Custom Font & Paragraph Styles
Apart from default built-in Word styles, developers can register reusable custom paragraph formats to unify typography across auto-generated Word content:
# Register user-defined paragraph style
custom_style = ParagraphStyle(doc)
custom_style.Name = "CustomStyle"
# Configure custom font attributes
custom_style.CharacterFormat.FontName = "Times New Roman"
custom_style.CharacterFormat.FontSize = 12
custom_style.CharacterFormat.Bold = False
custom_style.CharacterFormat.TextColor = Color.get_Gray()
doc.Styles.Add(custom_style)
# Bind custom style to target paragraph
para.ApplyStyle("CustomStyle")
# Set paragraph horizontal alignment
title.Format.HorizontalAlignment = HorizontalAlignment.Center
para.Format.HorizontalAlignment = HorizontalAlignment.Left
3. Advanced: Generate Rich Word Content in Python
These three practical scenarios cover top searched requirements: insert data tables, embed local images and add custom header/footer with auto page numbers in DOCX via Python code.
3.1 Insert Dynamic Data Tables Into Word DOCX
Populating structured business datasets into auto-adaptive Word tables is the most widely used function for automated report generation. The following example writes quarterly sales ledger into formatted DOCX tables:
from spire.doc import *
from spire.doc.common import *
doc = Document()
section = doc.AddSection()
section.PageSetup.Margins.All = 40
# Define table header and source business data
header = ["Month", "Product Line", "Revenue", "YoY Growth"]
data_list = [
["Jan", "Software Services", "23500", "6.2%"],
["Feb", "Hardware Products", "18900", "-2.1%"],
["Mar", "Outsourced O&M", "32100", "12.5%"]
]
# Initialize table: row count = header row + data rows, column count matches header
table = section.AddTable()
table.ResetCells(len(data_list)+1, len(header))
# Auto stretch table width to fit full page width
table.AutoFit(AutoFitBehaviorType.AutoFitToWindow)
# Apply built-in lightweight table theme
table.ApplyStyle(DefaultTableStyle.GridTable1LightAccent6)
# Fill bold-formatted table header cells
for col_idx, val in enumerate(header):
cell = table.Rows[0].Cells[col_idx]
cell.AddParagraph().AppendText(val).CharacterFormat.Bold = True
# Iteratively fill business detail rows
for row_idx, row_data in enumerate(data_list, start=1):
for col_idx, val in enumerate(row_data):
table.Rows[row_idx].Cells[col_idx].AddParagraph().AppendText(val)
doc.SaveToFile("business_data_table.docx", FileFormat.Docx)
doc.Dispose()
3.2 Embed Images Into Word Documents
Use Paragraph.AppendPicture() to insert local image assets into DOCX, with customizable dimension, center alignment and descriptive captions.
from spire.doc import *
from spire.doc.common import *
doc = Document()
section = doc.AddSection()
# Section heading
title = section.AddParagraph()
title.AppendText("Product Diagram")
title.ApplyStyle(BuiltinStyle.Heading1)
# Pre-image explanatory text
caption = section.AddParagraph()
caption.AppendText("The diagram below illustrates the product structure:")
# Insert and configure embedded image
image_para = section.AddParagraph()
picture = image_para.AppendPicture("product_diagram.png")
# Fix image dimension (unit: point)
picture.Width = 400
picture.Height = 300
# Center align the image container paragraph
image_para.Format.HorizontalAlignment = HorizontalAlignment.Center
# Bottom figure caption
caption_below = section.AddParagraph()
caption_below.AppendText("Figure 1 Product Structure Diagram")
caption_below.Format.HorizontalAlignment = HorizontalAlignment.Center
doc.SaveToFile("report_with_image.docx")
doc.Dispose()
3.3 Configure Header, Footer & Dynamic Page Numbers in DOCX
Headers and footers belong to section-level attributes bound to Section.HeadersFooters, supporting fixed header text and auto-calculated page/total-page fields for Python-generated Word files:
from spire.doc import *
from spire.doc.common import *
doc = Document()
section = doc.AddSection()
# Set page layout direction
section.PageSetup.Orientation = PageOrientation.Portrait
# Build right-aligned document header
header = section.HeadersFooters.Header.AddParagraph()
header.AppendText("Internal Company Document - Technical Report")
header.Format.HorizontalAlignment = HorizontalAlignment.Right
# Build centered footer with dynamic page / total page fields
footer = section.HeadersFooters.Footer.AddParagraph()
footer.AppendField("Page", FieldType.FieldPage)
footer.AppendText(" / ")
footer.AppendField("NumPages", FieldType.FieldNumPages)
footer.Format.HorizontalAlignment = HorizontalAlignment.Center
# Sample body content
content = section.AddParagraph()
content.AppendText("Report body content...")
doc.SaveToFile("with_header_footer.docx")
doc.Dispose()
4. Integrated End-to-End Demo: Auto-Generate Full Project Closing Report
This encapsulated function integrates all preceding features (header/footer, styled text, info tables, metric sheets) to produce a standardized project closing report via parameter input.
from spire.doc import *
from spire.doc.common import *
def generate_project_report(project_name, start_date, end_date, budget, metrics, summary):
"""
Generate standardized project closing Word report via Python
:param project_name: Target project full name
:param start_date: Project kickoff date
:param end_date: Project final delivery date
:param budget: Total project budget (unit: ten thousand CNY)
:param metrics: List of KPI tuples: (Metric Name, Actual Value, Target Value)
:param summary: Post-project overall summary text
"""
doc = Document()
section = doc.AddSection()
# Global page margin setup
section.PageSetup.Margins.Top = 70
section.PageSetup.Margins.Bottom = 70
section.PageSetup.Margins.Left = 60
section.PageSetup.Margins.Right = 60
# Centered document header
header = section.HeadersFooters.Header.AddParagraph()
header.AppendText("Project Closing Report - Internal Use")
header.Format.HorizontalAlignment = HorizontalAlignment.Center
# Auto page-number footer
footer = section.HeadersFooters.Footer.AddParagraph()
footer.AppendField("Page", FieldType.FieldPage)
footer.AppendText(" / ")
footer.AppendField("NumPages", FieldType.FieldNumPages)
footer.Format.HorizontalAlignment = HorizontalAlignment.Center
# Document main title
title = section.AddParagraph()
title.AppendText(f"{project_name} - Closing Report")
title.ApplyStyle(BuiltinStyle.Title)
title.Format.HorizontalAlignment = HorizontalAlignment.Center
title.Format.AfterSpacing = 20
# Part I: Basic project information table
heading_basic = section.AddParagraph()
heading_basic.AppendText("I. Basic Project Information")
heading_basic.ApplyStyle(BuiltinStyle.Heading1)
info_table = section.AddTable(True)
info_table.ResetCells(4, 2)
info_table.TableFormat.Borders.BorderType = BorderStyle.Single
info_data = [
("Project Name", project_name),
("Execution Period", f"{start_date} to {end_date}"),
("Budget Amount", f"{budget} ten thousand CNY"),
("Report Date", "June 2026")
]
for i, (key, value) in enumerate(info_data):
info_table.Rows[i].Cells[0].AddParagraph().AppendText(key).CharacterFormat.Bold = True
info_table.Rows[i].Cells[1].AddParagraph().AppendText(value)
# Part II: KPI completion statistics table
heading_metrics = section.AddParagraph()
heading_metrics.AppendText("II. Key Metrics Achievement")
heading_metrics.ApplyStyle(BuiltinStyle.Heading1)
metrics_table = section.AddTable(True)
metrics_table.ResetCells(len(metrics) + 1, 3)
metrics_table.TableFormat.Borders.BorderType = BorderStyle.Single
metric_headers = ["Metric Name", "Actual Value", "Target Value"]
# Fill table header with bold text
for idx, header in enumerate(metric_headers):
metrics_table.Rows[0].Cells[idx].AddParagraph().AppendText(header).CharacterFormat.Bold = True
# Fill KPI row content
for i, (name, actual, target) in enumerate(metrics):
metrics_table.Rows[i + 1].Cells[0].AddParagraph().AppendText(name)
metrics_table.Rows[i + 1].Cells[1].AddParagraph().AppendText(str(actual))
metrics_table.Rows[i + 1].Cells[2].AddParagraph().AppendText(str(target))
# Part III: Project summary paragraph
heading_summary = section.AddParagraph()
heading_summary.AppendText("III. Project Summary")
heading_summary.ApplyStyle(BuiltinStyle.Heading1)
summary_para = section.AddParagraph()
summary_para.AppendText(summary)
summary_para.ApplyStyle(BuiltinStyle.Normal)
# Export generated file and release resource
output_file = f"{project_name}_Closing_Report.docx"
doc.SaveToFile(output_file)
doc.Dispose()
print(f"Report generated successfully: {output_file}")
# Execute report generation entry
if __name__ == "__main__":
generate_project_report(
project_name="Next-Generation Data Analytics Platform",
start_date="2025-07-01",
end_date="2026-06-30",
budget=280,
metrics=[
("Data Processing Throughput (TPS)", 12500, 10000),
("Query Response Time (ms)", 85, 100),
("User Satisfaction Score", 4.8, 4.5),
("Feature Completion (%)", 98, 95)
],
summary="This project successfully completed the development and deployment of the next-generation data analytics platform. All key metrics met or exceeded expectations. The system has been running stably since launch and has received positive feedback from users. Subsequent phases will continue to advance AI analytics features and mobile support."
)
5. Summary
This complete tutorial covers the full end-to-end workflow to generate Word documents with Python. Developers can build DOCX files from scratch, add formatted text, business tables, embedded local images and customized header/footer with auto page numbers without installing Microsoft Word locally.
FAQ
Q1: Can I generate DOCX with Python without installing Microsoft Word?
A: Yes. Free Spire.Doc for Python is a standalone SDK with zero MS Word dependency; all DOCX creation runs purely via Python code.
Q2: Whatβs the limitation of Free Spire.Doc for Python free edition?
A: Free version caps at 500 paragraphs and 25 tables per single DOCX file; extra content gets automatically truncated after exceeding limits.
Q3: How to insert images and tables into Word document using Python?
A: Use AppendPicture() for image embedding and AddTable() + ResetCells() to initialize data tables, refer to Section 3.1 & 3.2 for ready-to-run code samples.
Q4: Is it possible to auto-generate full project report DOCX via Python?
A: Yes. Check the integrated function in Section 4; pass project basic info, budget and KPI data to generate formatted closing reports in one click.
Q5: Can Python edit existing finished Word DOCX files with Spire.Doc?
A: Supported via extended SDK features; load target DOCX and execute text replacement or content appending operations.
Top comments (0)