将excel文件中的信息读取后批量生成word文件

在日常办公过程中,可能需要把excel文件中的信息批量生成成百上千份word文档,便于打印、发邮件或存档等,比如根据excel中的合格人员招聘信息生成word合同文件,或是根据excel中的参会人员名单生成word参会通知等。

首先需要制作word模板,并在需要信息替换的位置设置域,选择MergeField,并配置域名。如本例设置了deptname和position两个域,需要从excel表格中读取后替换部门和职务的内容。还有年、月、日三个固定值的在程序里面直接写好后,填充在word中的year,month,day域。代码如下:

python 复制代码
import pandas as pd
from mailmerge import MailMerge
folder_path='.\\word\\' #文件夹相对路径
df=pd.read_excel(folder_path+'名单.xlsx') #通过read_excel方法读取excel数据存储到dataframe中
arr=df.to_numpy()   #将dataframe转换成二维数组
template=folder_path+'通知.docx' #word模版文件的位置
doc=MailMerge(template)
def merge(name,pos):
    doc.merge(deptname=name,
          position=pos,
          year='2024',
          month='11',
          day='27')
    doc.write(folder_path+f'{name}通知.docx')
for i in range(len(arr)):   #逐行遍历数组
    merge(arr[i][0],arr[i][1])
相关推荐
Jp7gnUWcI17 小时前
基于.NET操作Excel COM组件生成数据透视报表
.net·excel
pl4H522a618 小时前
Python 高效实现 Excel 转 TXT 文本
java·python·excel
开开心心_Every1 天前
实用PDF擦除隐藏信息工具,空白处理需留意
运维·服务器·网络·pdf·电脑·excel·依赖倒置原则
codeJinger1 天前
【Python】操作Excel文件
python·excel
城数派2 天前
谷歌18亿建筑足迹数据集 Google Open Buildings V3
数据库·arcgis·信息可视化·数据分析·excel
醉酒柴柴2 天前
word中没文字地方添加下划线方法
学习·word
whatzhang0072 天前
在 macOS 上从零配置 Vim:开启语法高亮 + 安装 vim-polyglot + 设置 gruvbox 主题
macos·vim·excel
fengyehongWorld2 天前
Excel 杂项知识
excel
开开心心就好3 天前
免费好用:PPT演示计时提醒工具
windows·计算机视觉·计算机外设·逻辑回归·excel·深度优先·csdn开发云
热爱生活的五柒3 天前
论文中如何设置图、表格和标题不分页
word·图表