python 通过word模板批量编辑word文档【docxtpl】

python编辑word文档,docxtpl是很合适的包,尤其是通过变量替换批量生成word文档,也能动态插入图片,并通过jinjia2语法对模板标签的管理,是的内容编辑更为灵活。

docxtpl英文文档

https://link.zhihu.com/?target=https%3A//docxtpl.readthedocs.io/en/latest/icon-default.png?t=M666https://link.zhihu.com/?target=https%3A//docxtpl.readthedocs.io/en/latest/

jinjia2基本语法:

  • 模板中的标签{{var}},var作为变量,可动态替换内容
  • 循环输出

{% for item in list_1 %}

{{ item}}

{% endfor %}

  • 逻辑判断

{% if if_var %}

If_var 判断是真的

{% endif %}

python通过字典形式载入变量,在render进行渲染

插入图片

先通过InlineImage对象,载入图片,设置图片尺寸

#(模板变量,图片地址,尺寸)
img_1 = InlineImage(tpl, image_descriptor=f'../files/01.png',width=Mm(145))

以下是demo

python代码

from docxtpl import DocxTemplate,InlineImage
# 引入尺寸参数
from docx.shared import Mm, Inches, Pt
# 加载模板
tpl = DocxTemplate('../files/word-tpl.docx')
# 载入图片
img_1 = InlineImage(tpl, image_descriptor=f'../files/01.png',width=Mm(145))
# 组合变量
context = {
    'img_1': img_1,
    'title_1': "标题",
    'text_1': "文字1",
    'text_2': "文字2",
    'if_var': True,
    'list_1': ["遍历01","遍历02","遍历03"]
}
# 渲染变量
tpl.render(context)
# 保存文件
tpl.save(f'../files/res.docx')

 结果展示

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值