关于 template-engine
template-engine 是一项通过将输入数据填入模板占位符来生成文档的技能。它采用基于 Jinja2 的语法,适用于 Word、Excel、PowerPoint 文档及批量邮件合并。
主要功能
- 01基于占位符生成文档
- 02Jinja2 风格变量与逻辑
- 03填充 Word 模板
- 04填充 Excel 模板
- 05批量邮件合并
适用场景
- 01根据数据生成个性化报告
- 02批量生成信件或合同
- 03按模板制作证书
- 04使用用户数据填写表单
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ claude-office-skills/ skills --skill template-engine安装后在 Claude Code 中输入/template-engine确认已加载。
详细介绍
模板引擎技能
概述
此技能支持基于模板生成文档——定义带占位符的模板,然后自动填充数据。适用于 Word、Excel、PowerPoint 等。
使用方法
- 描述你想完成的任务
- 提供所需的输入数据或文件
- 我会执行相应的操作
示例提示词:
- “批量合并生成信件/合同”
- “根据数据生成个性化报告”
- “根据模板创建证书”
- “使用用户数据自动填写表单”
领域知识
模板语法(基于 Jinja2)
{{ variable }} - Simple substitution
{% for item in list %} - Loop
{% if condition %} - Conditional
{{ date | format_date }} - Filter
Word 模板示例
from docxtpl import DocxTemplate
# Create template with placeholders:
# Dear {{ name }},
# Thank you for your order #{{ 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
# Usage
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
# Find and replace placeholders like {{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):
"""Generate documents for each row in 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"Generated: {output_path}")
# Usage with contacts.csv:
# name,email,company
# John,[email protected],Acme
# Jane,[email protected],Corp
mail_merge(
"templates/welcome_letter.docx",
"data/contacts.csv",
"output/letters"
)
高级:条件内容
from docxtpl import DocxTemplate
# Template with conditionals:
# {% if vip %}
# Thank you for being a VIP member!
# {% else %}
# Thank you for your purchase.
# {% endif %}
doc = DocxTemplate("template.docx")
doc.render({
"name": "John",
"vip": True,
"discount": 20
})
doc.save("output.docx")
最佳实践
- 使用清晰的占位符命名({{client_name}})
- 在渲染前验证数据
- 妥善处理缺失数据
- 对模板进行版本控制
安装
# Install required dependencies
pip install python-docx openpyxl python-pptx reportlab jinja2
资源
评论
支持 Markdown