博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
docxtpl的使用
阅读量:2061 次
发布时间:2019-04-29

本文共 973 字,大约阅读时间需要 3 分钟。

docxtpl的介绍

docxtpl 包可以加载docx格式的模板,来生成新的docx文件,通常用于生成docx报告。

安装

pip install docxtpl

使用

from docxtpl import DocxTemplatedoc = DocxTemplate("my_word_template.docx")context = { 'company_name' : "World company" }doc.render(context)doc.save("generated_doc.docx")

模板采用了jinja2语法,可参考

jinja2语法

{%p jinja2_tag %} for paragraphs #段落{%tr jinja2_tag %} for table rows #表格行{%tc jinja2_tag %} for table columns #表格列{%r jinja2_tag %} for runs #用于富文本

注意:不能在同一行中使用两次{%p, {%tr, {%tc ,{%r标签

{%p if display_paragraph %}Here is my paragraph {%p endif %}

应该这样

{%p if display_paragraph %}Here is my paragraph{%p endif %}

split和merge

{%- 表示接上一行-%} 表示接下一行

将标签写在一行

My house is located {% if living_in_town %} in urban area {% else %} in countryside {% endif %} and I love it.

也可以拆分成多行

My house is located{%- if living_in_town -%} in urban area{%- else -%} in countryside{%- endif -%} and I love it.

显示变量

{
{ }}{
{r }} 对于富文本{% cellbg %} #cell 颜色

参考资料

  • python处理word文档(docxtpl 中文说明文档)
  • docxtpl英文手册

转载地址:http://oeqlf.baihongyu.com/

你可能感兴趣的文章
算法工程师 面经2019年5月
查看>>
搜索架构师 一面面经2019年6月
查看>>
稻草人手记
查看>>
第一次kaggle比赛 回顾篇
查看>>
leetcode 50. Pow(x, n)
查看>>
leetcode 130. Surrounded Regions
查看>>
【托业】【全真题库】TEST2-语法题
查看>>
博客文格式优化
查看>>
【托业】【新托业全真模拟】疑难语法题知识点总结(01~05)
查看>>
【SQL】group by 和order by 的区别。
查看>>
【Python】详解Python多线程Selenium跨浏览器测试
查看>>
Jmeter之参数化
查看>>
Shell 和Python的区别。
查看>>
Python 列表(list)、字典(dict)、字符串(string)常用基本操作小结
查看>>
Loadrunner之https协议录制回放报错如何解决?(九)
查看>>
python中xrange和range的异同
查看>>
列表、元组、集合、字典
查看>>
【Python】easygui小甲鱼
查看>>
【Python】关于Python多线程的一篇文章转载
查看>>
【Pyton】【小甲鱼】文件
查看>>