基于docxtpl的模板生成Word

docxtpl是一个用于生成Microsoft Word文档的模板引擎库。它结合了docx模块和Jinja2模板引擎,使用户能够使用Microsoft Word模板文件并在其中填充动态数据。这个库提供了一种方便的方式来生成个性化的Word文档,并支持条件语句、循环语句和变量等控制结构,以满足不同的文档生成需求。

docxtpl是基于python-docx和jinja2开发出来的库。它通过对docx文档模板加载,使用类似jinja2网页模板开发的语法对其进行修改。这个库在功能上很专一,但功能强大,特别是在需要按照固定格式输出文档时,如数据库设计文档等。

安装docxtpl可以通过pip命令pip install docxtpl来完成。

docxtpl是一个方便、灵活的Python库,用于生成和修改Microsoft Word文档。

变量

python 复制代码
from docxtpl import DocxTemplate

tpl = DocxTemplate('tpl.docx')
context = {'name': '张三',  # 普通变量
           'address': {'province': '山东省', 'city': '青岛市', 'county': '市南区'},  # 字典
           'height': [30, 50, 150, 180]}  # 列表
tpl.render(context)
tpl.save('gen.docx')

模板

tpl.docx

python 复制代码
我叫{{name}},
在{{address.province}}{{address.city}}{{address.county}},
身高{{height|last}}。

生成

gen.docx

循环

段落

python 复制代码
from docxtpl import DocxTemplate

tpl = DocxTemplate('tpl.docx')
context = {'paragraphs': ["第一段", "第二段", "第三段", "第四段"]}
tpl.render(context)
tpl.save('gen.docx')

模板

python 复制代码
{% if paragraphs %}
{%p for p_tag in paragraphs %}
{{ p_tag}}
{%p endfor %}
{% endif %}

run

python 复制代码
from docxtpl import DocxTemplate

tpl = DocxTemplate('tpl.docx')
context = {'runs': ["第一个", "第二个", "第三个", "第四个"]}
tpl.render(context)
tpl.save('gen.docx')
python 复制代码
{%- if runs -%}
{%r for r_tag in runs %}{{ r_tag}}{%r endfor %}
{%- endif -%}

表格行

python 复制代码
from docxtpl import DocxTemplate

tpl = DocxTemplate('tpl.docx')
context = {'trs': ["第一个", "第二个", "第三个", "第四个"]}
tpl.render(context)
tpl.save('gen.docx')


表格列

python 复制代码
from datetime import datetime

from docxtpl import DocxTemplate

tpl = DocxTemplate('tpl.docx')
context = {
    'Company': '一家公司',
    'date': datetime.now().strftime("%d.%m.%Y"),
    'col_labels': ['产品', '分类', '价格', '库存'],
    'tbl_contents': [
        {'label': 'Item 1', 'cols': ['Laptop', 'Electronics', '$900', '50'], 'bg': 'E37222'},
        {'label': 'Item 2', 'cols': ['T-shirt', 'Apparel', '$15', '200'], 'bg': '07889B'},
        {'label': 'Item 3', 'cols': ['Coffee Mug', 'Kitchenware', '$8', '150'], 'bg': 'E37222'},
        {'label': 'Item 4', 'cols': ['Smartphone', 'Electronics', '$700', '100'], 'bg': '07889B'},
    ],
}

tpl.render(context)
tpl.save('gen.docx')

相关链接

https://docxtpl.readthedocs.io/en/latest/

相关推荐
Eternity_GQM1 天前
【Word VBA Zotero 引用宏错误分析与改正指南】【解决[21–23]参考文献格式插入超链接问题】
开发语言·c#·word
小付同学呀3 天前
word——删除最后一页空白页
word
我在北国不背锅3 天前
基于Java的Markdown转Word工具(标题、段落、表格、Echarts图等)
java·word·echarts·markdown
全宇宙最最帅气的哆啦A梦小怪兽3 天前
【word】一次选中全部表格,宏方法
word
揭老师高效办公4 天前
WPS文字和Word文档如何选择多个不连续的行、段
word·wps文字
Kyln.Wu5 天前
【python实用小脚本-182】Python一键爬取今日新闻:5分钟生成Word+CSV——再也不用复制粘贴
开发语言·python·word
揭老师高效办公6 天前
在Word和WPS文字一页中实现一栏与多栏混排
word·wps文字
菜鸟-要努力6 天前
pdf文件转word免费使用几个工具
pdf·word
天蓝蓝的本我6 天前
word的正则替换
word
海哥编程9 天前
python使用python-docx自动化操作word
python·自动化·word