超简单Python将指定数据插入到docx模板渲染并生成

最近有一个需求,制作劳动合同表,要从excel表格中将每个人的数据导入到docx劳动合同中,重复量很大,因此可以使用python高效解决。为了让模板内容不变动,这里使用了类似jinja2的渲染引擎,使用{{ }}插值表达式把数据插入进去。也可以使用{% %}循环,条件语法等。

docx模板如下(在需要插值的位置填充 {{}} 表达式):

在这里插入图片描述

首先安装docxtpl

$ pip install docxtpl

python代码如下:

from docxtpl import DocxTemplate
tpl = DocxTemplate('劳动合同.docx')
#这些字段从csv中获取
context = {
   "name": name,
   "department": department,
   "position": position,
   "time": time,
   "id": id_card,
   "addr": addr,
}
tpl.render(context)
tpl.save("{}的劳动合同.docx".format(name))

运行后就可以在docx中看到效果,{{ field }}这里已经被context里面的字段替换了,非常简单!

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!