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

相关推荐
东方佑3 小时前
使用 Python 自动化 Word 文档样式复制与内容生成
python·自动化·word
wqqqianqian2 天前
国产linux系统(银河麒麟,统信uos)使用 PageOffice在线编辑word文件保存数据同时保存文件
linux·word·信创·国产·保存·pageoffice·在线编辑
余子桃2 天前
Python实现markdown文件转word
python·word·markdown
一只特立独行的兔先森2 天前
WordZero:让Markdown与Word文档自由转换的Golang利器
golang·word·word自动化
CodeCraft Studio2 天前
文档处理组件Aspose.Words 25.5全新发布 :六大新功能与性能深度优化
word·aspose·aspose.words·word文档转换
weixin_472339462 天前
python批量解析提取word内容到excel
python·word·excel
俱会一处2 天前
将word文件转为kindle可识别的azw3文件的方法
word
cccl.2 天前
Java在word中指定位置插入图片。
java·word
CodeCraft Studio3 天前
国产化Word处理控件Spire.Doc教程:Java实现HTML 转Word自动化
java·html·word
neimeng03 天前
Deepseek/cherry studio中的Latex公式复制到word中
word