template-engine

template-engine

熱門

自動填入文件模板與資料 - 適用於任何格式的合併列印

316星標
70分支
更新於 2026/1/31
SKILL.md
唯讀
名稱
template-engine
描述

自動填入文件模板與資料 - 適用於任何格式的合併列印

版本
1.0

模板引擎技能

概述

此技能支援基於模板的文件生成 - 定義含有佔位符的模板,然後自動填入資料。適用於 Word、Excel、PowerPoint 等格式。

使用方式

  1. 描述你想完成的事項
  2. 提供所需的輸入資料或檔案
  3. 我將執行對應的操作

範例提示詞:

  • 「大量信件/合約的合併列印」
  • 「從資料生成個人化報告」
  • 「從模板建立證書」
  • 「用使用者資料自動填寫表單」

領域知識

模板語法(基於 Jinja2)

{{ variable }}           - 簡單取代
{% for item in list %}   - 迴圈
{% if condition %}       - 條件判斷
{{ date | format_date }} - 過濾器

Word 模板範例

from docxtpl import DocxTemplate

# 建立含有佔位符的模板:
# 親愛的 {{ name }},
# 感謝您的訂單 #{{ order_id }}...

def fill_template(template_path: str, data: dict, output_path: str):
    doc = DocxTemplate(template_path)
    doc.render(data)
    doc.save(output_path)
    return output_path

# 使用方式
fill_template(
    "templates/order_confirmation.docx",
    {
        "name": "John Smith",
        "order_id": "ORD-12345",
        "items": [
            {"name": "Product A", "qty": 2, "price": 29.99},
            {"name": "Product B", "qty": 1, "price": 49.99}
        ],
        "total": 109.97
    },
    "output/confirmation_john.docx"
)

Excel 模板

from openpyxl import load_workbook
import re

def fill_excel_template(template_path: str, data: dict, output_path: str):
    wb = load_workbook(template_path)
    ws = wb.active
    
    # 尋找並取代 {{name}} 這類佔位符
    for row in ws.iter_rows():
        for cell in row:
            if cell.value and isinstance(cell.value, str):
                for key, value in data.items():
                    placeholder = "{{" + key + "}}"
                    if placeholder in cell.value:
                        cell.value = cell.value.replace(placeholder, str(value))
    
    wb.save(output_path)
    return output_path

大量生成(合併列印)

import csv
from pathlib import Path

def mail_merge(template_path: str, data_csv: str, output_dir: str):
    """為 CSV 中的每一行生成文件。"""
    
    Path(output_dir).mkdir(exist_ok=True)
    
    with open(data_csv) as f:
        reader = csv.DictReader(f)
        
        for i, row in enumerate(reader):
            output_path = f"{output_dir}/document_{i+1}.docx"
            fill_template(template_path, row, output_path)
            print(f"已生成:{output_path}")

# 使用 contacts.csv:
# name,email,company
# John,john@example.com,Acme
# Jane,jane@example.com,Corp

mail_merge(
    "templates/welcome_letter.docx",
    "data/contacts.csv",
    "output/letters"
)

進階:條件內容

from docxtpl import DocxTemplate

# 含有條件判斷的模板:
# {% if vip %}
# 感謝您成為 VIP 會員!
# {% else %}
# 感謝您的購買。
# {% endif %}

doc = DocxTemplate("template.docx")
doc.render({
    "name": "John",
    "vip": True,
    "discount": 20
})
doc.save("output.docx")

最佳實務

  1. 使用清晰的佔位符命名(如 {{client_name}})
  2. 在渲染前驗證資料
  3. 妥善處理遺漏資料
  4. 對模板進行版本控制

安裝

# 安裝所需相依套件
pip install python-docx openpyxl python-pptx reportlab jinja2

資源