python之使用docxtpl渲染word模板

目录

word模板内容

docxtpl 使用的 Jinja2 模板语法

A1内容:{{A1}}

A2内容:{{A2}}

A3内容:{{A3}}

人员信息:

姓名 年龄 性别
{%tr for item in person %}
{{item.name}} {{item.age}} {{item.sex}}
{%tr endfor %}

安全信息:

IP地址 端口 规则名称
{%tr for item in secure %}
{{item.ip}} {{item.port}} {{item.rule}}
{%tr endfor %}

列表数据:

{% for val in dataList -%}

{{val}}

{% endfor -%}

python代码

python 复制代码
# -*- coding: utf-8 -*-

from docxtpl import DocxTemplate
import dmPython

# ---------------------- 1. 达梦数据库配置 ----------------------
DM_CONFIG = {
    "user": "SYSDBA",          # 用户名
    "password": "SYSDBA",      # 密码
    "server": "localhost",     # IP
    "port": 5236,              # 端口
    "database": "DAMENG"       # 库名
}


def get_dm_data(sql):
    """从达梦查询数据,返回 docxtpl 需要的字典"""
    global cursor
    conn = None
    try:
        # 连接达梦
        conn = dmPython.connect(**DM_CONFIG)
        cursor = conn.cursor()

        # 写你的查询 SQL
        # sql = 'SELECT id, name, age, phone, address, create_time FROM user_info WHERE id = 1001'
        cursor.execute(sql)
        # 获取列名
        columns = [desc[0] for desc in cursor.description]
        # 获取一行数据
        # row = cursor.fetchone()
        # 获取所有数据
        rows = cursor.fetchall()

        # 自动组装成字典:{字段名: 值}
        # data_dict = dict(zip(columns, row))

        # 转为 [{}, {}, {}] 格式(docxtpl 循环专用)
        # 返回 docxtpl 需要的字典,需要根据业务需要进行组装
        data_dict = [dict(zip(columns, row)) for row in rows]

        return data_dict
    finally:
        if conn:
            cursor.close()
            conn.close()


def template_render(doc, context):
    doc.render(context)


def generate_example():
    pass


if __name__ == '__main__':
    # 1. 加载 Word 模板
    document = DocxTemplate("template.docx")

    # 2. 从达梦数据库获取要替换的数据
    """
      json中的key为模板中的占位符,value为实际替换后的内容
      注意:数据库返回的结果集可能只有一层JSON数据,比如:{"name": "张三","age":"11","sex":"man"},实际需要如2-1的样本数据,需要单独组装数据
    """
    # 写你的查询 SQL
    sql = 'SELECT id, name, age, phone, address, create_time FROM user_info WHERE id = 1001'
    # data = get_dm_data(sql)

    analyzer = dict(A1="A1值",A2="A2值",A3="A3值",A4=4,A5=5)
    table1 = [{"name": "张三","age":"11","sex":"man"},{"name": "王五","age":"13","sex":"woman"}]
    table2 = [{"ip": "192.168.0.11","port":"8081","rule":"test"},{"ip": "192.168.0.12","port":"8082","rule":"test2"},{"ip": "192.168.0.13","port":"8083","rule":"tes3"}]
    dataList = ["项一","项二","项三","项四"]

    data = {**analyzer,"person": table1,"secure": table2,"dataList": dataList}

    # 3. 执行替换
    template_render(document, data)

    # 4. 保存生成的新文档,名字自定义
    document.save("生成结果.docx")
    print("Word 文档生成完成!")
相关推荐
净水深流4 分钟前
中国冷链冷库行业数据分析:从规模扩张到技术驱动
大数据·数据库·人工智能·冷库冷链
东莞市云毅网络有限公司16 分钟前
PDF 表格抽取的三条技术路线对比:规则、库解析与版面识别
python·sqlite·自动化运维·geo·数据监测
李兆龙的博客36 分钟前
从一到无穷大 #94:ClickHouse TimeSeries——时间线组织与 Prometheus 兼容性
数据库
冰暮流星38 分钟前
事务的四个特性(ACID)详解
数据库
byte轻骑兵1 小时前
时序数据库选型全指南|大数据工业场景Apache IoTDB落地实操
大数据·数据库·人工智能·apache iotdb
外收内放1 小时前
Python与AI应用(项目开发实战:AI智能伴侣第一版)
python·学习·ai编程
绘梨衣5471 小时前
慢SQL排查手册
python·sql
Sirens.1 小时前
MySQL数据库:JDBC编程
数据库·mysql
troy1281 小时前
告别 Copilot?Codex、Claude Code、DeepSeek Harness、Kimi、ChatGPT 哪个更适合本地化部署,更有性价比?
人工智能·python·开源软件
IvanCodes1 小时前
Python 文件操作(十二):文件与目录的读写
开发语言·python