用Python代码实现将exl表格内容,批量写到word里面

一、问题分析

key words:EXL表格、Word模板、批量

自动化办公有时候经常需要批量修改或者生成一些文档数据。本文是我在实际处理问题时,通过查找资料改写成的方法,能够实现将已知EXL表格中的数据一一插入到Word模板里,再生成新的Word文档,存于指定的路径下。

二、docxtpl、openpyxl的安装

右键“开始”点击Windows PowerShell,输入:

pip install docxtpl
回车

pip install openpyxl
回车

出现如下界面,则两个库安装成功。
在这里插入图片描述
具体的库函数安装操作步骤,可参照我其他文章,如:
《在Pycharm引入numpy、matplotlib库的一些操作记录》

三、代码实现

1、准备工作

1、数据源:离职信息表:
在这里插入图片描述

2、模板:离职申请书的Word文档
在这里插入图片描述
3、需要将2的文档,在要填的信息处,做好如下指引:

在这里插入图片描述

2、代码如下

from docxtpl import DocxTemplate
from openpyxl import load_workbook
import os


# 加载要填入的数据
exl = load_workbook(r"F:\deal_office\deal_exl2word\离职信息表.xlsx")
table = exl['Sheet1']
contexts = []
for row in range(2, table.max_row + 1):
    f_name = table["A"+str(row)].value # 定义生成文件的名字
    name = table["B" + str(row)].value # 姓名
    id_num = table["C" + str(row)].value # 身份证号
    gender = table["D" + str(row)].value # 性别
    in_time = table["E" + str(row)].value # 入职时间
    in_time = str(in_time)[:-9] # 入职时间是带时分秒的,本次取到日不带时分秒
    out_time = table["F" + str(row)].value # 离职时间
    out_time = str(out_time)[:-9] # 同入职时间一致
    # 本条区别于离职时间,是落款,要取出年月日
    out_date_y = str(out_time)[:4]
    out_date_m = str(out_time)[5:7]
    out_date_d = str(out_time)[8:10]



    context = {"f_name": f_name, "name": name, "id_num": id_num, "gender": gender, "in_time": in_time, "out_time": out_time,
               "out_date_y": out_date_y, "out_date_m": out_date_m, "out_date_d": out_date_d} # 以字典形式储存到context中


    contexts.append(context) # 将每条字典,存到contexts数组中
contexts
# 创建要保存的文件夹
path = r"F:\deal_office\deal_exl2word\result"
if not os.path.exists(path):
    os.makedirs(path)
n = 0
for context in contexts:
    print(context)
    n += 1

    tpl = DocxTemplate(r"F:\deal_office\deal_exl2word\离职申请模板.docx")
    tpl.render(context)
    tpl.save(path + "./{}的离职证明.docx".format(context["f_name"]))
    
print('\n一共生成{}份文件'.format(n))

运行结果如下:
在这里插入图片描述
在这里插入图片描述

  • 5
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值