1.实现目的
邮件合并也有其缺陷,那就是每次合并数据都需操作插入合并域,如果经常需要根据数据生成固定模板word文件,那么就显得很麻烦
显然利用程序固定数据替换模式就极为方便,需要生成文件时可以一键操作
2.代码实现
import os.path import xlrd from mailmerge import MailMerge docx = r'D:\Users\86156\PycharmProjects\pythonProject\邮件合并\1.docx' xlsx = r'D:\Users\86156\PycharmProjects\pythonProject\邮件合并\1.xlsx' filepath = os.path.dirname(docx) workbook = xlrd.open_workbook(xlsx) worksheet = workbook.sheet_by_index(0) nrow = worksheet.nrows for key in range(1, nrow): with MailMerge(docx) as doc: doc.merge(name=str(worksheet.cell_value(key, 1)), position=str(worksheet.cell_value(key, 2))) output = filepath + r'\证明-{}.docx'.format(str(worksheet.cell_value(key, 1))) doc.write(output) workbook = xlrd.open_workbook(xlsx) worksheet = workbook.sheet_by_index(0) nrow = worksheet.nrows list1 = [] # 空列表 fo