跳转至

模板概述

本页面介绍 Symphra Excel 的模板引擎功能。

什么是模板

模板允许您使用预先设计好的 Excel 文件作为基础,然后通过变量替换动态填充数据。

基本用法

创建模板工作簿

from symphra_excel.templates import TemplateWorkbook

template = TemplateWorkbook("template.xlsx")

data = {
    "title": "2024年销售报表",
    "total": 12345.67,
}

template.render(data)

template.save("output.xlsx")

模板语法

变量替换

在 Excel 模板中使用 {{variable}} 语法:

{{title}}
{{company_name}}
{{date}}

数据渲染

template_data = {
    "title": "月度报表",
    "company_name": "ABC公司",
    "date": "2024-01-01",
}

template.render(template_data)

完整示例

示例1: 简单模板

from symphra_excel.templates import TemplateWorkbook

with TemplateWorkbook("invoice_template.xlsx") as template:
    data = {
        "invoice_no": "INV-2024-001",
        "customer": "张三",
        "amount": 5000.00,
        "date": "2024-01-15",
    }

    template.render(data)
    template.save("invoice_001.xlsx")

示例2: 批量生成

from symphra_excel.templates import TemplateWorkbook

customers = [
    {"name": "张三", "amount": 5000},
    {"name": "李四", "amount": 8000},
    {"name": "王五", "amount": 6000},
]

template_path = "invoice_template.xlsx"

for idx, customer in enumerate(customers, start=1):
    with TemplateWorkbook(template_path) as template:
        data = {
            "invoice_no": f"INV-2024-{idx:03d}",
            "customer": customer["name"],
            "amount": customer["amount"],
        }
        template.render(data)
        template.save(f"invoice_{idx:03d}.xlsx")

优势

  • 可视化设计: 在 Excel 中直接设计模板布局
  • 复用性强: 一个模板可生成多个文件
  • 易于维护: 修改模板无需改代码
  • 支持复杂格式: 保留原有样式和格式

下一步