模板标签主要来自jinja2,可以了解其语法:
模板设计者文档 — Jinja2 2.7 documentation
docxtpl英文手册:
Welcome to python-docx-template’s documentation! — python-docx-template 0.9.x documentation
from docxtpl import DocxTemplate, RichText
# 初始化模板对象
tpl = DocxTemplate("./temp.docx")
# 待填充的字典数据,其中key对应word模板中的填充名
context = {
"日期": '2021-10-01',
"作者": '张玉龙',
}
# 开始渲染context数据到模板文件中
tpl.render(context=context)
tpl.save("示例结果文档.docx")
效果展示
from docxtpl import DocxTemplate, RichText
# 初始化模板对象
tpl = DocxTemplate("./temp.docx")
# 待填充的字典数据,其中key对应word模板中的填充名
context = {
"table": [{"app_level": 'A类', "app": "营业", "db_name": "YY", "db_type": "PDB", "run": RichText('READ ONLY', color='FF0000', size=16, ), },
{"app_level": 'B类', "app": "账务", "db_name": "ZW", "db_type": "PDB", "run": RichText('READ WRITE', color='000000', size=16, ), },
{"app_level": 'C类', "app": "报表", "db_name": "BB", "db_type": "PDB", "run": RichText('MOUNTED', color='FF0000', size=16, ), },
{"app_level": 'D类', "app": "计费", "db_name": "JF", "db_type": "PDB", "run": RichText('READ WRITE', color='000000', size=16, ), },
],
}
# 开始渲染context数据到模板文件中
tpl.render(context=context)
tpl.save("示例结果文档.docx")
from docxtpl import DocxTemplate, RichText
# 初始化模板对象
tpl = DocxTemplate("./temp.docx")
# 定义字典 context 填充渲染模板的数据
context = {}
# 巡检脚本生成的事件列表
events = [['/oracle目录使用率超过90%', '操作系统配置', '4.2', '尽快处理'],
['表空间XXX使用率超过90%', '数据库配置', '5.7', '尽快处理'],
['资源ora.scan1.vip状态为OFFLINE', '集群配置', '6.1', '尽快处理'],
['磁盘组XXX使用率超过90%', 'ASM配置', '8.1', '尽快处理'],
['存在已知比特币勒索对象', '数据库风险评估', '9.4', '尽快处理'],
['存在无效索引', '数据库对象信息', '10.2', ''],
['XXX SQL 执行效率低', '数据库性能评估', '11.2', ''],
['无RMAN物理备份', '数据库备份评估', '12.1', ''],
]
# 定义一个临时字典和列表
tmp_aa = {}
tmp_bb= []
# 待填充的字典数据,其中key对应word模板中的填充名
for event_row in events:
tmp_aa["desc"] = event_row[0]
tmp_aa["type"] = event_row[1]
tmp_aa["chap"] = event_row[2]
if event_row[3] == "尽快处理":
tmp_aa["time"] = RichText(event_row[3], color='FF0000', size=16, )
else:
tmp_aa["time"] = RichText(event_row[3], color='000000', size=16, )
tmp_bb.append(tmp_aa)
tmp_aa = {}
context["event_table"] = tmp_bb
# 开始渲染context数据到模板文件中
tpl.render(context=context)
tpl.save("示例结果文档.docx")
---------未完待续