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

相关推荐
PfCoder8 分钟前
WinForm真入门(23)---PictureBox 控件详细用法
开发语言·windows·c#·winform
Legendary_00810 分钟前
Type-C 一拖二快充线:突破单口限制的技术逻辑
c语言·开发语言
过期动态16 分钟前
Java开发中的@EnableWebMvc注解和WebMvcConfigurer接口
java·开发语言·spring boot·spring·tomcat·maven·idea
CoLiuRs16 分钟前
语义搜索系统原理与实现
redis·python·向量·es
zhihuaba19 分钟前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python
u01092727120 分钟前
Python Web爬虫入门:使用Requests和BeautifulSoup
jvm·数据库·python
csbysj202038 分钟前
Web 标准
开发语言
老姚---老姚1 小时前
在windows下编译go语言编写的dll库
开发语言·windows·golang
diediedei1 小时前
模板编译期类型检查
开发语言·c++·算法
Stream_Silver1 小时前
【Agent学习笔记3:使用Python开发简单MCP服务】
笔记·python