Python 批量生成准考证 - 使用 MailMerge 和 DocxTemplate

本代码使用 Python 的 MailMergeDocxTemplate 库,实现批量生成准考证的功能。它从 Excel 文件读取数据,并将数据填充到 Word 模板中,生成多个准考证文档。

代码

# Import necessary libraries
from mailmerge import MailMerge
from docxtpl import DocxTemplate
import pandas as pd

# Set the file paths for the template and data
template_path = r'C:\Users\yezi\Desktop\准考证\准考证模板(3).docx'
data_path = r'C:\Users\yezi\Desktop\准考证\准考证数据.xlsx'

# Load the data into a pandas dataframe
data_df = pd.read_excel(data_path)

# Initialize an empty list to store the filled-in templates
templates = []

# Loop through the dataframe and fill in each template
for index, row in data_df.iterrows():
    # Create a new DocxTemplate object from the template file path
    tpl = DocxTemplate(template_path)
    # Render the template with the data from the current row
    tpl.render(row.to_dict())
    # Add the filled-in template to the list
    templates.append(tpl)

# Merge the filled-in templates into a single document
merge = MailMerge()
merge.merge_templates(templates, separator='page_break')

# Save the merged document to a new file
merge.write(r'C:\Users\yezi\Desktop\准考证\merged_doc.docx')

代码说明

  1. 导入必要的库: mailmerge, docxtplpandas 库分别用于 Word 文件合并、Word 模板渲染和 Excel 数据读取。
  2. 设置文件路径: 设定准考证模板文件路径 (template_path) 和准考证数据文件路径 (data_path)。
  3. 读取数据: 使用 pandas 库读取 Excel 文件并将其转换为 DataFrame
  4. 初始化模板列表: 创建一个空列表 templates 用于存储填充后的模板。
  5. 遍历数据并填充模板: 使用 for 循环遍历 DataFrame 的每一行,并使用 DocxTemplate 对象渲染模板。将渲染后的模板添加到 templates 列表中。
  6. 合并模板: 使用 MailMerge 对象将 templates 列表中的所有模板合并到一个文档中。
  7. 保存文件: 将合并后的文档保存到指定路径。

注意事项

  • 确保你已经安装了 mailmergedocxtpl 库。
  • 将代码中的文件路径替换为你实际的文件路径。
  • 准考证模板文件应该包含需要填充的字段,例如姓名、准考证号等。
  • 准考证数据文件应该包含与模板字段对应的列,例如姓名、准考证号等。

其他功能

本代码提供了一个简单的批量生成准考证的功能,你可以根据需要扩展功能,例如:

  • 添加自定义页面设置,例如页眉页脚、边距等。
  • 添加其他数据源,例如数据库或文本文件。
  • 实现其他功能,例如生成二维码或条形码。
Python 批量生成准考证 - 使用 MailMerge 和 DocxTemplate

原文地址: https://www.cveoy.top/t/topic/n9q9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录