from mailmerge import MailMergefrom docxtpl import DocxTemplateimport pandas as pd# 准考证模板文件路径template_path = rCUsersyeziDesktop准考证准考证模板3docx# 准考证数据列表data_dataframe = pdread_excelrCUsersyeziDesktop准考证准
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'
原文地址: https://www.cveoy.top/t/topic/fhDf 著作权归作者所有。请勿转载和采集!