Python 批量生成Word 合同

要使用 Python 批量生成 Word 合同,您可以遵循以下步骤:

1. 整理 Excel 数据

假设您有一个 Excel 文件,其中第一行为字段名称,下面是对应的内容。举个例子,Excel 数据如下:

姓名 地址 电话 日期
张三 北京市某街道 13800138000 2025-01-07
李四 上海市某街道 13900139000 2025-01-08

2. 准备合同模版

您需要一个 Word 合同模板,其中包含需要替换的占位符。假设您的合同模板 (contract_template.docx) 是一个 Word 文件,里面有类似 {``{姓名}}{``{地址}}{``{电话}}{``{日期}} 的占位符。

3. Python 脚本

以下是一个 Python 脚本的示例,使用 pandas 读取 Excel 数据,python-docx 操作 Word 文档:

安装所需的库
bash 复制代码
pip install pandas openpyxl python-docx
Python 脚本
python 复制代码
import pandas as pd
from docx import Document
import os

# 读取 Excel 文件
excel_file = 'contracts.xlsx'  # 替换为你的 Excel 文件路径
df = pd.read_excel(excel_file)

# 合同模版路径
template_path = 'contract_template.docx'  # 替换为你的 Word 模版文件路径

# 输出文件夹
output_dir = 'generated_contracts'
os.makedirs(output_dir, exist_ok=True)

# 函数:根据数据替换模板中的字段
def generate_contract(data_row, template_path, output_path):
    # 读取合同模版
    doc = Document(template_path)
    
    # 遍历文档中的所有段落,替换占位符
    for para in doc.paragraphs:
        for key, value in data_row.items():
            para.text = para.text.replace(f'{{{{ {key} }}}}', str(value))
    
    # 保存生成的合同
    doc.save(output_path)

# 遍历 Excel 数据,并生成合同
for index, row in df.iterrows():
    # 获取每行数据
    data_row = row.to_dict()

    # 合同输出路径
    output_path = os.path.join(output_dir, f'contract_{index + 1}.docx')
    
    # 生成合同
    generate_contract(data_row, template_path, output_path)

    print(f'合同 {index + 1} 已生成: {output_path}')

print("所有合同生成完毕!")
代码解释:
  1. 读取 Excel 数据 :使用 pandas.read_excel() 读取 Excel 文件并转换为 DataFrame,确保 Excel 的第一行是字段名。
  2. 合同模版替换 :使用 python-docx 打开 Word 模板文件,并通过替换文档中各段落的占位符(如 {``{姓名}})来填充数据。
  3. 保存文件 :将修改后的 Word 文件保存到指定的输出目录,每个文件以 contract_{index}.docx 命名。

4. 流程

  • 准备一个包含数据的 Excel 文件,字段名称与合同模板中的占位符相匹配。
  • 编写并运行 Python 脚本,生成每个合同。
  • 输出文件将保存在 generated_contracts 文件夹中。

更多定制化需求,接需求:

signmaker AI Contract Generator 智能定制化合同

相关推荐
IT小盘4 小时前
03-大模型API不只是发送Prompt-流式输出超时重试与异常处理
人工智能·python·prompt
Zzz不能停5 小时前
个人博客系统系统---测试报告【笔耕云】
python·功能测试·自动化·压力测试
互联网中的一颗神经元6 小时前
小白python入门 - 39. 采集流水线小项目
开发语言·python
Wang's Blog6 小时前
Go-Zero 项目开发22:用户群聊功能的实现与完善
开发语言·golang
a1117767 小时前
坦克大战3D Three.js 3D (开源项目)
开发语言·javascript·3d
郭老二7 小时前
【Python】常用模块:xmlrpc
python
名字还没想好☜7 小时前
Python itertools 实战:用 groupby、chain、islice 优雅处理大数据流
linux·windows·python·迭代器·itertools
威联通网络存储8 小时前
TS-h2490FU在面板制造Array段AOI缺陷画廊中的并联
python·制造
Wang's Blog8 小时前
Go-Zero项目开发24: 基于Bitmap实现群聊消息已读未读
开发语言·后端·golang
接针9 小时前
UV 常用命令
python·uv