Python使用Free Spire.Doc for Python实现自动化生成Word文档
在自动化办公场景中,批量生成合同、分析报告或项目说明书是常见需求。如果仍依赖手动复制粘贴,不仅效率低下,格式统一与结构规范也难以保证。本文将介绍如何使用免费库 Free Spire.Doc for Python 以编程方式生成 Word 文档,涵盖从基础文档创建到表格、图片等丰富内容的综合示例。
环境准备
Free Spire.Doc for Python 是一个用于处理 Word 文档的 Python 库,支持在不依赖 Microsoft Word 环境的情况下创建、读取、修改和转换 Word 文档(包括 .doc 和 .docx 格式)。
使用 pip 即可完成安装:
pip install Spire.Doc.Free
注意:免费版面存在固定容量限制:单文档最大支持 500 个段落、25 张数据表,超出限额内容会被自动截断。该限制基本可以满足日常报表、测试文档、小型台账的自动化生成需求,大批量超长篇文档需更换其他方案选型。
安装完成后,在 Python 脚本中导入所需模块:
from spire.doc import * from spire.doc.common import *
基础示例:使用 Python 创建 Word 文档
1. 基础文档结构
Word 文档的组织层次如下:
Document → Section → Paragraph → TextRange。
Document 是整个文档的根对象;每个 Document 至少包含一个 Section;Section 是页面布局的基本单位,可以独立设置页眉页脚和页面属性;Paragraph 是文本容器;TextRange 则对应段落中的一段连续文本。
以下代码创建一份基础的 Word 文档:
# 创建 Document 对象
doc = Document()
# 添加一节
section = doc.AddSection()
# 设置页面边距(单位:磅)
section.PageSetup.Margins.Top = 60
section.PageSetup.Margins.Bottom = 60
section.PageSetup.Margins.Left = 70
section.PageSetup.Margins.Right = 70
# 添加标题段落
title = section.AddParagraph()
title.AppendText("2026年度技术报告")
title.ApplyStyle(BuiltinStyle.Title)
# 添加一级标题
heading1 = section.AddParagraph()
heading1.AppendText("一、项目概况")
heading1.ApplyStyle(BuiltinStyle.Heading1)
# 添加正文段落
para = section.AddParagraph()
para.AppendText("本报告总结了2026年度技术团队在核心产品研发、性能优化和用户体验提升等方面的工作成果。")
para.ApplyStyle(BuiltinStyle.Normal)
# 保存文档
doc.SaveToFile("demo.docx")
doc.Dispose()
2. 自定义字体和段落样式
除了使用 Word 内置样式(如 Title、Heading1 等),还可以创建自定义样式:
# 创建自定义段落样式
custom_style = ParagraphStyle(doc)
custom_style.Name = "CustomStyle"
custom_style.CharacterFormat.FontName = "宋体"
custom_style.CharacterFormat.FontSize = 12
custom_style.CharacterFormat.Bold = False
custom_style.CharacterFormat.TextColor = Color.get_Gray()
doc.Styles.Add(custom_style)
# 应用到段落
para.ApplyStyle("CustomStyle")
段落对齐方式可以通过 Format 属性设置:
title.Format.HorizontalAlignment = HorizontalAlignment.Center para.Format.HorizontalAlignment = HorizontalAlignment.Left
进阶场景 1:动态插入业务数据表格
自动化报表最常用场景:读取结构化数据并写入 Word 表格,支持自适应页面宽度、内置表格样式,示例写入简易销售台账数据:
from spire.doc import *
from spire.doc.common import *
doc = Document()
section = doc.AddSection()
section.PageSetup.Margins.All = 40
# 表头数据与业务明细数据
header = ["月份", "产品线", "营收金额(元)", "同比增幅"]
data_list = [
["1月", "软件服务", "235000", "6.2%"],
["2月", "硬件产品", "189000", "-2.1%"],
["3月", "运维外包", "321000", "12.5%"]
]
# 创建4列4行表格
table = section.AddTable()
table.ResetCells(len(data_list)+1, len(header))
# 表格自动适配页面宽度
table.AutoFit(AutoFitBehaviorType.AutoFitToWindow)
# 套用内置浅色表格样式
table.ApplyStyle(DefaultTableStyle.GridTable1LightAccent6)
# 填充表头
for col_idx, val in enumerate(header):
cell = table.Rows[0].Cells[col_idx]
cell.AddParagraph().AppendText(val).CharacterFormat.Bold = True
# 填充明细数据
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("业务数据表.docx", FileFormat.Docx)
doc.Dispose()
进阶场景 2:插入图片
使用 Paragraph.AppendPicture() 方法可以将图片插入到 Word 文档的段落中。下面是一个在正文中插入产品图片的示例:
from spire.doc import *
from spire.doc.common import *
doc = Document()
section = doc.AddSection()
# 添加标题
title = section.AddParagraph()
title.AppendText("产品示意图")
title.ApplyStyle(BuiltinStyle.Heading1)
# 添加用于说明的正文
caption = section.AddParagraph()
caption.AppendText("下图展示了产品结构示意图:")
# 插入图片
image_para = section.AddParagraph()
picture = image_para.AppendPicture("product_diagram.png")
# 设置图片尺寸(单位:点)
picture.Width = 400
picture.Height = 300
# 设置图片居中对齐
image_para.Format.HorizontalAlignment = HorizontalAlignment.Center
# 添加图片下方的说明文字
caption_below = section.AddParagraph()
caption_below.AppendText("图1 产品结构示意图")
caption_below.Format.HorizontalAlignment = HorizontalAlignment.Center
doc.SaveToFile("report_with_image.docx")
doc.Dispose()
进阶场景 3:添加页眉和页脚
页眉和页脚属于 Section 级别的组件,需要添加到 Section 对应的 HeadersFooters 属性中:
from spire.doc import *
from spire.doc.common import *
doc = Document()
section = doc.AddSection()
# 设置页面方向(横向或纵向)
section.PageSetup.Orientation = PageOrientation.Portrait
# 添加页眉
header = section.HeadersFooters.Header.AddParagraph()
header.AppendText("公司内部资料 - 技术报告")
header.Format.HorizontalAlignment = HorizontalAlignment.Right
# 添加页脚并插入页码
footer = section.HeadersFooters.Footer.AddParagraph()
footer.AppendField("Page", FieldType.FieldPage)
footer.AppendText(" / ")
footer.AppendField("NumPages", FieldType.FieldNumPages)
footer.Format.HorizontalAlignment = HorizontalAlignment.Center
# 添加正文内容
content = section.AddParagraph()
content.AppendText("报告正文内容...")
doc.SaveToFile("带页眉页脚.docx")
doc.Dispose()
综合示例:自动生成项目报告文档
以下综合示例整合了前文介绍的各项功能,演示如何自动生成一份完整的项目结项报告文档:
from spire.doc import *
from spire.doc.common import *
def generate_project_report(project_name, start_date, end_date, budget, metrics, summary):
"""
生成项目结项报告文档
参数:
project_name: 项目名称
start_date: 开始日期
end_date: 结束日期
budget: 项目预算(万元)
metrics: 关键指标列表,每个元素为(指标名称, 实际值, 目标值)
summary: 项目总结文本
"""
doc = Document()
section = doc.AddSection()
# 页面设置
section.PageSetup.Margins.Top = 70
section.PageSetup.Margins.Bottom = 70
section.PageSetup.Margins.Left = 60
section.PageSetup.Margins.Right = 60
# 页眉
header = section.HeadersFooters.Header.AddParagraph()
header.AppendText("项目结项报告 - 内部使用")
header.Format.HorizontalAlignment = HorizontalAlignment.Center
# 页脚(自动页码)
footer = section.HeadersFooters.Footer.AddParagraph()
footer.AppendField("Page", FieldType.FieldPage)
footer.AppendText(" / ")
footer.AppendField("NumPages", FieldType.FieldNumPages)
footer.Format.HorizontalAlignment = HorizontalAlignment.Center
# 主标题
title = section.AddParagraph()
title.AppendText(f"{project_name} - 结项报告")
title.ApplyStyle(BuiltinStyle.Title)
title.Format.HorizontalAlignment = HorizontalAlignment.Center
title.Format.AfterSpacing = 20
# 基本信息区域
heading_basic = section.AddParagraph()
heading_basic.AppendText("一、项目基本信息")
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), ("执行周期", f"{start_date} 至 {end_date}"),
("预算金额", f"{budget} 万元"), ("报告日期", "2026年6月")]
for i, (key, value) in enumerate(info_data):
info_table.Rows[i].Cells[0].AddParagraph().AppendText(key)
info_table.Rows[i].Cells[1].AddParagraph().AppendText(value)
# 设置第一列样式(标签列加粗)
info_table.Rows[i].Cells[0].AddParagraph().ApplyStyle(BuiltinStyle.Normal)
# 关键指标表格
heading_metrics = section.AddParagraph()
heading_metrics.AppendText("二、关键指标完成情况")
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 = ["指标名称", "实际值", "目标值"]
for idx, header in enumerate(metric_headers):
metrics_table.Rows[0].Cells[idx].AddParagraph().AppendText(header)
metrics_table.Rows[0].Cells[idx].AddParagraph().ApplyStyle(BuiltinStyle.Normal)
# 填充指标数据
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))
# 项目总结
heading_summary = section.AddParagraph()
heading_summary.AppendText("三、项目总结")
heading_summary.ApplyStyle(BuiltinStyle.Heading1)
summary_para = section.AddParagraph()
summary_para.AppendText(summary)
summary_para.ApplyStyle(BuiltinStyle.Normal)
# 保存文档
output_file = f"{project_name}_结项报告.docx"
doc.SaveToFile(output_file)
doc.Dispose()
print(f"报告已生成:{output_file}")
# 使用示例
if __name__ == "__main__":
generate_project_report(
project_name="新一代数据分析平台",
start_date="2025-07-01",
end_date="2026-06-30",
budget=280,
metrics=[
("数据处理吞吐量(TPS)", 12500, 10000),
("查询响应时间(ms)", 85, 100),
("用户满意度评分", 4.8, 4.5),
("功能完成度(%)", 98, 95)
],
summary="本项目成功完成了新一代数据分析平台的研发和部署工作。各项关键指标均达到或超过预期目标,系统上线后运行稳定,获得了用户的积极反馈。后续将在二期项目中继续推进AI分析功能和移动端支持的开发。"
)
补充拓展:常用衍生能力
- 列表生成:通过
ListFormat.ApplyStyle()快速生成有序 / 无序列表,适配条款、清单类文档; - 格式转换:支持 MD、HTML 文件直接载入后另存为
docx,实现 Markdown 文档批量转 Word; - 文档编辑:可加载已有
docx文件,检索替换指定关键词、追加新段落,实现文档二次修改。
小结
以上内容演示了一套完整的 Word 文档生成方案,从创建基础文档结构到添加表格、图片、页眉页脚等丰富内容,均可通过简洁的 API 在代码中实现,无需依赖 Microsoft Word 环境。适用于自动生成报表、批量处理合同文档、输出项目报告等开发任务,满足日常工作中的文档自动化处理需求。
到此这篇关于Python使用Free Spire.Doc for Python实现自动化生成Word文档的文章就介绍到这了,更多相关Python生成Word内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!


最新评论