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

相关推荐
RainSerein17 小时前
Laravel8中使用phpword生成word文档
word·php·laravel
qq_3938282220 小时前
办公文档批量打印器 Word、PPT、Excel、PDF、图片和文本,它都支持批量打印。
windows·word·powerpoint·excel·软件需求
_oP_i11 天前
实现 “WebView2 获取word选中内容
开发语言·c#·word
LENG_Lingliang11 天前
word出现由WPS切换后公式异常无法删除的情况处理
word·wps·mathtype
贤和兄11 天前
使用docx4j 实现word转pdf(linux乱码处理)
linux·pdf·word
开开心心就好12 天前
高效批量转换Word到PDF的方法
javascript·安全·智能手机·pdf·word·objective-c·lisp
response_L12 天前
麒麟v10、uos系统在线批量生成pdf文件
java·pdf·word·pageoffice·在线编辑
清风细雨_林木木13 天前
私有 Word 文件预览转 PDF 实现方案
pdf·word
一只秋田犬13 天前
基于 Apache POI 实现的 Word 操作工具类
word
清风细雨_林木木14 天前
.docx 和 .doc 都是 Word 文档格式的区别
word