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英文手册