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

相关推荐
行云流水剑5 分钟前
【学习记录】如何使用 Python 提取 PDF 文件中的内容
python·学习·pdf
gregmankiw5 分钟前
C#调用Rust动态链接库DLL的案例
开发语言·rust·c#
roman_日积跬步-终至千里20 分钟前
【Go语言基础【20】】Go的包与工程
开发语言·后端·golang
呆萌的代Ma36 分钟前
Cursor实现用excel数据填充word模版的方法
word·excel
秦少游在淮海41 分钟前
C++ - string 的使用 #auto #范围for #访问及遍历操作 #容量操作 #修改操作 #其他操作 #非成员函数
开发语言·c++·stl·string·范围for·auto·string 的使用
const5441 小时前
cpp自学 day2(—>运算符)
开发语言·c++
心扬1 小时前
python生成器
开发语言·python
mouseliu1 小时前
python之二:docker部署项目
前端·python
阿蒙Amon1 小时前
06. C#入门系列【自定义类型】:从青铜到王者的进阶之路
开发语言·c#
虾球xz1 小时前
CppCon 2015 学习:CLANG/C2 for Windows
开发语言·c++·windows·学习