🧩 一、技术选型
库 功能 安装
python-docx 创建、修改 .docx
,读写文字/段落/表格/样式 pip install python-docx
pandas(可选) 批量读取 Excel/CSV,作为数据源 pip install pandas
🎯 二、典型使用场景
合同/证书/报告批量生成
Word 模板里放好占位符
{{name}}
、{{date}}
,一行 Excel 数据生成一份 Word。自动化报告
把跑数结果直接写进 Word,段落+表格+图表一次性搞定。
质检/审核
自动扫描 Word 里的关键字段、表格内容,做校验。
🛠️ 三、核心 API 速查表
任务 代码片段
打开文档 doc = Document('模板.docx')
查找所有段落 for p in doc.paragraphs:
查找所有表格 for t in doc.tables:
替换段落文字 p.text = p.text.replace('{{name}}', '张三')
替换表格文字 cell.text = cell.text.replace('{{amount}}', '¥1,234')
添加段落 doc.add_paragraph('新段落')
添加表格 table = doc.add_table(rows=3, cols=2)
保存文档 doc.save('结果.docx')
📄 四、最小可运行示例
场景:根据 Excel 批量生成“录用通知书”
📋 1. 准备模板 template.docx
录用通知书
尊敬的 {{name}} 先生/女士:
您已被我公司 {{department}} 录用,职位 {{position}},月薪 {{salary}} 元,请于 {{onboard_date}} 报到。
📊 2. Excel info.xlsx
name department position salary onboard_date
张三 研发部 后端 15000 2025-09-01
李四 产品部 产品经理 18000 2025-09-03
🧑💻 3. 批量生成脚本 gen_offer.py
from docx import Document
import pandas as pd
import os
# 1. 读取数据
df = pd.read_excel('info.xlsx')
# 2. 输出目录
os.makedirs('output', exist_ok=True)
# 3. 循环生成
for _, row in df.iterrows():
doc = Document('template.docx')
# 替换段落
for p in doc.paragraphs:
for key, val in row.items():
p.text = p.text.replace(f'{{{key}}}', str(val))
# 替换表格(如果有)
for t in doc.tables:
for row in t.rows:
for cell in row.cells:
for key, val in row.items():
cell.text = cell.text.replace(f'{{{key}}}', str(val))
# 保存
filename = f"output/{row['name']}的录用通知书.docx"
doc.save(filename)
print('全部生成完毕!')
⚙️ 五、进阶技巧
需求 做法
保留原格式(加粗、颜色) 用 runs
级替换,见下方
插入图片 doc.add_picture('sign.png', width=Inches(2))
设置字体 run.font.name = '宋体'
(需配合 rPr
样式)
生成 PDF 先用 docx2pdf
或 LibreOffice 命令行转
邮件自动发送 生成 Word 后用 smtplib
发附件
🧪 六、保留格式的“run”级替换
模板里占位符如果设置了加粗/颜色,直接改 paragraph.text
会清掉样式,需要逐 run
替换:
def replace_text_runs(paragraph, old, new):
"""保留样式替换"""
for run in paragraph.runs:
if old in run.text:
run.text = run.text.replace(old, new)
✅ 七、踩坑提示
坑 解决方案
.doc
不支持 只能处理 .docx
,老版 Word 先另存为
中文乱码 保证模板文件 utf-8,必要时用 python-docx-template
图片路径 使用绝对路径或 os.path.abspath
表格样式 复杂样式建议直接做在模板里,只替换内容
📦 八、一键模板仓库(推荐)
不想自己搭脚手架?直接 clone 开源项目:
-
支持 Jinja2 语法:
{{name}}
、{% for item in items %}
,极致简洁。
🎯 总结一句话
“把 Word 当模板,Excel 当数据源,Python 当胶水,一键批量生成。”