基于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/

相关推荐
da-peng-song8 小时前
python学习—详解word邮件合并
python·学习·word
棉晗榜1 天前
Aspose.Words导出word,服务器用内存流处理,不生成磁盘文件
c#·word·aspose.words
吉普赛的歌1 天前
C#: 用Libreoffice实现Word文件转PDF
pdf·word
188_djh2 天前
# 使用python写一个PDF文件转换成word 文件
python·pdf·word·python-docx·pypdf2·python3.9·pdf_to_word.py
GoMaxAi3 天前
金融行业 AI 报告自动化:Word+PPT 双引擎生成方案
人工智能·unity·ai作画·金融·自动化·aigc·word
安全菜鸟3 天前
DeepSeek 接入 Word 完整教程
开发语言·c#·word
徐赛俊3 天前
使用 VBA 宏创建一个选择全部word图片快捷指令,进行图片格式编辑
word
liwulin05063 天前
【WORD】批量将doc转为docx
开发语言·c#·word
杂学者3 天前
python办公自动化------word文件的操作
python·word
阳洞洞4 天前
leetcode 139. Word Break
算法·leetcode·word·动态规划