python编辑word文档,docxtpl是很合适的包,尤其是通过变量替换批量生成word文档,也能动态插入图片,并通过jinjia2语法对模板标签的管理,是的内容编辑更为灵活。
docxtpl英文文档
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')
结果展示