python+docxtpl:word文件模版渲染

目录

操作流程

加载模版

模版渲染

文件保存

python-docx库结合

模版渲染说明

变量值的获取

模板代码语句

遍历生成列表


docxtpl使用jinja2作为框架的模板系统,基于python-docx,同样可以使用python-docx库的一些方法,如添加段落,添加图片、列表等。

安装:pip install docxtpl -i https://pypi.mirrors.ustc.edu.cn/simple/

使用一般步骤:模版文件加载->模版渲染->文件保存。

操作时会用到的相关方法类:加载模板DocxTemplate、设置图片InlineImage、设置文本样式RichText

操作流程

加载模版

from docxtpl import DocxTemplate, InlineImage, RichText
from docx.shared import Mm, Inches, Pt, Cm

doc = DocxTemplate(r'C:\Users\Administrator\Desktop\模版文件.docx') 

模版渲染

# 模版变量
context = {'title': RichText('页眉测试', color='FFDD00', bold=True),
           'name': '张非',
           'remark': {'remark1': '备注1', 'remark2': '备注2', 'remark3': ['备注3-1', '备注3-2''备注3-3']},
           'img': InlineImage(doc, r'C:\Users\Administrator\Desktop\testfile\测试图片\124.png', width=Cm(6),
                              anchor='https://www.baidu.com/'),  # 插入图片
           'table_datas': [
               {'name': '刘唐', 'masterwork': '《水浒》', 'bg': 'FF0000', 'other': ['刘', '唐']},
               {'name': '悟空', 'masterwork': '《西游》', 'other': ['悟', '空']},
               {'name': RichText('甄士隐', color='FFDD00', bold=False), 'masterwork': '《红楼》', 'bg': '8888FF',
                'other': ['甄', '士', '隐']},
               {'name': RichText('诸葛尚', color='FF0000', bold=True), 'masterwork': '《三国》', 'other': ['诸葛', '尚']}
           ],
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值