docxtpl的使用

docxtpl的介绍

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

pip install docxtpl

使用

from docxtpl import DocxTemplate

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

模板采用了jinja2语法,可参考http://docs.jinkan.org/docs/jinja2/templates.html

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.

显示变量

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

参考资料

猜你喜欢

转载自blog.csdn.net/a854596855/article/details/114920047