新建一个word文档模板
编写代码:
from docxtpl import DocxTemplate
tpl = DocxTemplate('templates/dynamic_table_tpl.docx')
context = {
'col_labels' : ['fruit', 'vegetable', 'stone', 'thing'],
'tbl_contents': [
{'label': 'yellow', 'cols': ['banana', 'capsicum', 'pyrite', 'taxi']},
{'label': 'red', 'cols': ['apple', 'tomato', 'cinnabar', 'doubledecker']},
{'label': 'green', 'cols': ['guava', 'cucumber', 'aventurine', 'card']},
]
}
tpl.render(context)
tpl.save('output/dynamic_table.docx')可以生成以下效果:
书写格式注意事项:
Important:
Always put space after a jinja2 starting var/tag delimiter and a space before the ending one :
Avoid:
{{myvariable}}
{%if something%}
Use instead:
{{ myvariable }}
{% if something %}