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

相关推荐
打码人的日常分享14 小时前
运维服务方案,运维巡检方案,运维安全保障方案文件
大数据·运维·安全·word·安全架构
揭老师高效办公15 小时前
在Word和WPS文字的表格中快速输入连续的星期、月、日
word·wps
gc_22991 天前
C#测试调用OpenXml操作word文档的基本用法
c#·word·openxml
vfvfb1 天前
word文档结尾批量插入图片 docx批量插入图片 指定几张
word·docx插入图片·word批量插入图片·word文档批量插入图片
老马啸西风2 天前
sensitive-word 敏感词性能提升14倍优化全过程 v0.28.0
安全·开源·nlp·word·敏感词·sensitive-word
象骑士Hack2 天前
Word 常用快捷键大全:提升文档处理效率的必备技巧
word
会飞的小菠菜2 天前
如何根据Excel数据表生成多个合同、工作证、录取通知书等word文件?
word·excel·模板·数据表·生成文件
IT小农工3 天前
Windows 文件资源管理器无法预览文件内容word、ppt、excel、pdf
windows·word·powerpoint
BillKu3 天前
在 Delphi 5 中获取 Word 文档页数的方法
word·delphi
IssacNew3 天前
【原创软件】第14期:FastWordReplace-Word文字批量替换工具V1.1
word·文字替换·批量替换