Python使用Free Spire.Doc for Python实现自动化生成Word文档

 更新时间:2026年06月04日 14:57:00   作者:咕白m625  
本文将介绍如何使用免费库 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 至少包含一个 SectionSection 是页面布局的基本单位,可以独立设置页眉页脚和页面属性;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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 使用python提取PowerPoint中的音频和视频

    使用python提取PowerPoint中的音频和视频

    将多种格式的媒体内容进行重新利用(如PowerPoint演示中的音频和视频)是非常有价值的,从演示文稿中提取这些媒体文件可以为多媒体内容的多次使用提供更大的灵活性,本文将演示如何使用Python从PowerPoint演示文稿中提取音频和视频,需要的朋友可以参考下
    2024-09-09
  • Python字符串拼接六种方法介绍

    Python字符串拼接六种方法介绍

    这篇文章主要介绍了Python字符串拼接六种方法介绍,具有一定借鉴价值,需要的朋友看可以参考下。
    2017-12-12
  • Python基于百度AI的文字识别的示例

    Python基于百度AI的文字识别的示例

    本篇文章主要介绍了Python基于百度AI的文字识别的示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-04-04
  • python代码 输入数字使其反向输出的方法

    python代码 输入数字使其反向输出的方法

    今天小编就为大家分享一篇python代码 输入数字使其反向输出的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-12-12
  • Python解析toml配置文件的方法分享

    Python解析toml配置文件的方法分享

    在开发过程中,配置文件是少不了的,而且配置文件是有专门的格式的,比如:ini,yaml,toml等等。本文带大家来看看Python如何解析toml文件,需要的可以参考一下
    2022-09-09
  • OpenCV使用KNN完成OCR手写体识别

    OpenCV使用KNN完成OCR手写体识别

    这篇文章主要为大家介绍了OpenCV使用KNN完成OCR手写体识别示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-05-05
  • 在Python下利用OpenCV来旋转图像的教程

    在Python下利用OpenCV来旋转图像的教程

    这篇文章主要介绍了在Python下利用OpenCV来旋转图像的教程,代码和核心的算法都非常简单,需要的朋友可以参考下
    2015-04-04
  • Python+PyQt5实现网口功能测试详解

    Python+PyQt5实现网口功能测试详解

    这篇文章主要为大家详细介绍了Python+PyQt5实现网口功能测试的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2024-02-02
  • 详细聊聊为什么Python中0.2+0.1不等于0.3

    详细聊聊为什么Python中0.2+0.1不等于0.3

    最近在学习过程中发现在计算机JS时发现了一个非常有意思事,0.1+0.2的结果不是0.3,而是0.30000000000000004,下面这篇文章主要给大家介绍了关于为什么Python中0.2+0.1不等于0.3的相关资料,需要的朋友可以参考下
    2022-12-12
  • Python定时任务实现方案

    Python定时任务实现方案

    这篇文章主要介绍了Python定时任务实现的方案,定时执行的任务,可以是一段bash命令,也可以是一个脚本文件。通常用于我们需要在特定时刻做事情,下面来看看文章详细内容,需要的朋友可以参考一下
    2021-11-11

最新评论