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 智能定制化合同

相关推荐
kyle~4 分钟前
FastAPI --- 将业务能力以 API 的形式提供给外部系统
python·fastapi·前后端
aiotto资源分享24 分钟前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
利威尔xu35 分钟前
Go Mutex 饥饿模式:正常模式等待者饿死,1ms 阈值自动切换崩溃
开发语言·后端·面试·golang·并发编程
梯度下降者1 小时前
Python信号量,条件变量,事件学习
python·条件变量·事件·信号量·线程通信
LSDlsdoo2 小时前
冷却液与油污飞溅工况下,国产接近开关怎么选?五步工程化选型方法
其他·自动化
MSTcheng.2 小时前
【AI应用实战】用 FastAPI + SSE 做一个自己的 AI 聊天网页:流式输出、多轮对话与完整源码
人工智能·python·大模型·fastapi·sse·ai聊天助手
乌暮2 小时前
少写重复 CRUD:用大白话搞懂 MyBatis-Plus
java·开发语言·spring boot·面试·mybatis
不绝1912 小时前
Lua基础语法入门:注释、变量类型与字符串操作
开发语言·lua
the局外人3 小时前
Python 实战检索优化:BM25、向量与重排
数据库·后端·python
__underline__3 小时前
冷门Python知识点006篇:Python 类体里的名字,能被"凭空造出来"
后端·python