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 文档生成完成!")
相关推荐
花酒锄作田15 小时前
Pydantic校验配置文件
python
hboot16 小时前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
GBASE20 小时前
G术时刻 |GBase 8s数据库事务并发控制之封锁技术介绍(下)
数据库
ZhengEnCi1 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi1 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽1 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187911 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
xiezhr1 天前
逛GitHub发现了一款免费的带AI功能的数据库管理工具
数据库·ai编程·dba
Warson_L2 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅2 天前
海天线算法的前世今生
python·计算机视觉