第 8 课:Excel 生成模式
AI 怎么生成 Excel 文件?
和"文档自动化工厂"一样,这里用的也是代码生成模式:
graph TD
A["AI 理解需求"] --> B["AI 写 Python 代码(用 openpyxl / pandas)"]
B --> C["Bash 执行 Python 代码"]
C --> D["代码输出 .xlsx 文件"]
D --> E["recalc.py 验证公式"]
E -->|"有错误"| F["AI 修复"] --> B
E -->|"无错误"| G["完成"]
不同的是: - 文档自动化工厂用 JavaScript + docx 库 生成 Word - 这里用 Python + openpyxl/pandas 生成 Excel
AI 写的 Python 代码长什么样?
假设用户说:"帮我做一个 2024 年月度销售报表"。AI 会写出类似这样的代码:
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
wb = Workbook()
ws = wb.active
ws.title = "Monthly Sales 2024"
# ===== 表头样式 =====
header_font = Font(name='Arial', size=11, bold=True, color='FFFFFF')
header_fill = PatternFill(start_color='217346', fill_type='solid') # Excel绿
thin_border = Border(
left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin')
)
# ===== 标题行 =====
headers = ['Month', 'Revenue', 'Cost', 'Profit', 'Margin']
for col, header in enumerate(headers, 1):
cell = ws.cell(row=1, column=col, value=header)
cell.font = header_font
cell.fill = header_fill
cell.alignment = Alignment(horizontal='center')
cell.border = thin_border
# ===== 数据行(蓝色 = 用户可修改的输入) =====
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
input_font = Font(name='Arial', size=11, color='0000FF') # 蓝色=输入
for i, month in enumerate(months, 2): # 从第2行开始
ws.cell(row=i, column=1, value=month).border = thin_border
# Revenue 和 Cost 是蓝色(用户输入)
rev_cell = ws.cell(row=i, column=2, value=0)
rev_cell.font = input_font
rev_cell.number_format = '#,##0'
rev_cell.border = thin_border
cost_cell = ws.cell(row=i, column=3, value=0)
cost_cell.font = input_font
cost_cell.number_format = '#,##0'
cost_cell.border = thin_border
# Profit = Revenue - Cost(公式!不是硬编码!)
profit_cell = ws.cell(row=i, column=4)
profit_cell.value = f'=B{i}-C{i}' # ✅ 公式
profit_cell.number_format = '#,##0'
profit_cell.border = thin_border
# Margin = Profit / Revenue(带除零保护)
margin_cell = ws.cell(row=i, column=5)
margin_cell.value = f'=IF(B{i}=0,0,D{i}/B{i})' # ✅ 防 #DIV/0!
margin_cell.number_format = '0.0%'
margin_cell.border = thin_border
# ===== 汇总行 =====
total_row = len(months) + 2
ws.cell(row=total_row, column=1, value='TOTAL').font = Font(bold=True)
for col in [2, 3, 4]: # Revenue, Cost, Profit
col_letter = get_column_letter(col)
cell = ws.cell(row=total_row, column=col)
cell.value = f'=SUM({col_letter}2:{col_letter}{total_row-1})' # ✅ 公式
cell.font = Font(bold=True)
cell.number_format = '#,##0'
cell.border = thin_border
# Margin 汇总(加权平均)
margin_total = ws.cell(row=total_row, column=5)
margin_total.value = f'=IF(B{total_row}=0,0,D{total_row}/B{total_row})'
margin_total.font = Font(bold=True)
margin_total.number_format = '0.0%'
margin_total.border = thin_border
# ===== 列宽自适应 =====
ws.column_dimensions['A'].width = 12
for col in range(2, 6):
ws.column_dimensions[get_column_letter(col)].width = 15
# ===== 冻结表头 =====
ws.freeze_panes = 'A2'
# ===== 保存 =====
wb.save('Monthly_Sales_2024.xlsx')
print('Sales report generated successfully!')
注意 AI 遵守的规范
对照上一课讲的 SKILL.md 规范,看看 AI 是怎么执行的:
1. 公式优先 ✅
# Profit 用公式,不是硬编码
cell.value = f'=B{i}-C{i}'
# 汇总用 SUM 公式
cell.value = f'=SUM(B2:B13)'
2. 防止公式错误 ✅
# Margin 用 IF 避免除以零
cell.value = f'=IF(B{i}=0,0,D{i}/B{i})'
# ↑ 如果 Revenue=0,就返回 0,不会出 #DIV/0!
3. 颜色规范 ✅
# 蓝色 = 用户可修改的输入值
input_font = Font(color='0000FF')
# 黑色(默认)= 公式计算结果
4. 专业格式 ✅
# 数字格式
cell.number_format = '#,##0' # 千位分隔符
cell.number_format = '0.0%' # 百分比
# 冻结表头
ws.freeze_panes = 'A2'
# 边框
thin_border = Border(left=Side(style='thin'), ...)
pandas 的使用场景
如果用户上传了一个 CSV 或 Excel 要做分析,AI 更可能用 pandas:
import pandas as pd
# 读取用户上传的数据
df = pd.read_excel('./problems/uploaded_data.xlsx')
# 数据分析
summary = df.groupby('Region').agg({
'Sales': ['sum', 'mean', 'count'],
'Profit': 'sum'
}).round(2)
# 导出为新的 Excel
with pd.ExcelWriter('Analysis_Report.xlsx', engine='openpyxl') as writer:
df.to_excel(writer, sheet_name='Raw Data', index=False)
summary.to_excel(writer, sheet_name='Summary')
但如果需要精细格式控制,AI 会在 pandas 导出后再用 openpyxl 来美化:
# 第一步:pandas 做数据分析
df = pd.read_excel(...)
summary = df.groupby(...).agg(...)
# 第二步:openpyxl 做精细排版
from openpyxl import load_workbook
wb = load_workbook('Analysis_Report.xlsx')
ws = wb['Summary']
# 添加格式、公式、冻结等
for cell in ws[1]:
cell.font = Font(bold=True, color='FFFFFF')
cell.fill = PatternFill(start_color='217346', fill_type='solid')
wb.save('Analysis_Report.xlsx')
多工作表的例子
AI 也能生成多工作表的复杂 Excel:
wb = Workbook()
# 工作表 1:原始数据
ws_data = wb.active
ws_data.title = "Raw Data"
# ... 填入数据 ...
# 工作表 2:月度汇总
ws_monthly = wb.create_sheet("Monthly Summary")
# ... 用公式引用 Raw Data 的数据 ...
# 例如:='Raw Data'!B2
# 工作表 3:仪表盘
ws_dashboard = wb.create_sheet("Dashboard")
# ... 用公式引用 Monthly Summary 的汇总数据 ...
wb.save('Multi_Sheet_Report.xlsx')
代码生成 → 执行 → 验证 的完整循环
graph TD
S1["第 1 步:Skill → 读取 xlsx SKILL.md"]
S2["第 2 步:Read → 读取 docx-js.md(如果需要的话)"]
S3["第 3 步:Write → 写 generate_report.py"]
S4["第 4 步:Bash → python3 generate_report.py"]
S5["第 5 步:Bash → python3 recalc.py report.xlsx"]
S1 --> S2 --> S3 --> S4
S4 -->|"成功"| S5
S4 -->|"报错"| FIX1["AI 看错误信息 → 修改代码"] --> S4
S5 -->|"status: success"| DONE["完成"]
S5 -->|"status: errors_found"| FIX2["AI 修复公式"] --> S4
和 Word 生成的对比
| Word 生成(文档自动化工厂) | Excel 生成(本项目) | |
|---|---|---|
| AI 写的代码 | JavaScript | Python |
| 用的库 | docx-js | openpyxl + pandas |
| 核心挑战 | 排版精确(字号、间距) | 公式正确(无 #REF! 等) |
| 验证方式 | 检查文件是否存在 | recalc.py 验证公式 |
| 格式规范 | 字号、边距约束 | 颜色规范、公式规则 |
共同点:都是"AI 写代码 → 执行代码 → 产出文件"的代码生成模式。
本课小结
- AI 通过写 Python 代码来生成 Excel(代码生成模式)
- openpyxl 处理格式和公式,pandas 处理数据分析
- AI 严格遵守 SKILL.md 的规范:公式优先、零错误、颜色规范
- 有完整的验证闭环:生成 → recalc.py 验证 → 有错就修 → 再验证
课后练习
- 让 AI 生成一个 Excel,然后打开 AI 写的 Python 脚本看看
- 修改 AI 的代码,加一列新数据,手动运行看看效果
- 故意引入一个 #REF! 错误(引用不存在的单元格),运行 recalc.py 看看报告