xiaohongshu
xiaohongshu
excel-report-generator
Automatically generate Excel reports from data sources including CSV, databases, or Python data structures. Supports data analysis reports, business reports, data export, and template-based report generation using pandas and openpyxl. Activate when users mention Excel, spreadsheet, report generat...
Full skill instructions
自动化 Excel 报表生成工具,支持从多种数据源生成专业的 Excel 报告。
这个 Skill 可以帮助你:
从原始数据生成包含统计分析、透视表和可视化图表的综合报告。
示例请求:
定期生成标准化的业务报告,如销售报告、KPI 仪表板等。
示例请求:
将数据库查询结果或系统数据导出为格式化的 Excel 文件。
示例请求:
基于预定义的 Excel 模板填充动态数据。
示例请求:
从 CSV 生成报表:
请从 sales_data.csv 生成一个销售分析报表,包含:
- 按产品分类的销售汇总
- 月度销售趋势图
- Top 10 产品排名
从 DataFrame 生成报表:
我有一个 pandas DataFrame,帮我生成 Excel 报表,包括:
- 数据透视表
- 条件格式高亮异常值
- 自动筛选和冻结首行
使用模板:
基于 templates/monthly_report.xlsx 模板,填充当月数据并生成报告
当用户请求生成 Excel 报表时,遵循以下步骤:
import pandas as pd
from openpyxl import load_workbook
from openpyxl.styles import Font, PatternFill, Alignment
from openpyxl.utils.dataframe import dataframe_to_rows
# 读取数据
df = pd.read_csv('data.csv')
# 或从数据库
# df = pd.read_sql(query, connection)
# 数据清洗和转换
df_clean = df.dropna()
# 统计分析
summary = df.groupby('category').agg({
'sales': ['sum', 'mean', 'count'],
'profit': 'sum'
})
# 使用 pandas ExcelWriter
with pd.ExcelWriter('output.xlsx', engine='openpyxl') as writer:
# 写入原始数据
df_clean.to_excel(writer, sheet_name='Raw Data', index=False)
# 写入汇总数据
summary.to_excel(writer, sheet_name='Summary')
# 获取 workbook 进行格式化
workbook = writer.book
worksheet = writer.sheets['Summary']
# 标题样式
header_font = Font(bold=True, color='FFFFFF')
header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')
# 应用样式到标题行
for cell in worksheet[1]:
cell.font = header_font
cell.fill = header_fill
cell.alignment = Alignment(horizontal='center')
# 列宽自动调整
for column in worksheet.columns:
max_length = 0
column_letter = column[0].column_letter
for cell in column:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
worksheet.column_dimensions[column_letter].width = max_length + 2
from openpyxl.chart import BarChart, Reference
# 创建图表
chart = BarChart()
chart.title = "Sales by Category"
chart.x_axis.title = "Category"
chart.y_axis.title = "Sales"
# 数据引用
data = Reference(worksheet, min_col=2, min_row=1, max_row=10)
categories = Reference(worksheet, min_col=1, min_row=2, max_row=10)
chart.add_data(data, titles_from_data=True)
chart.set_categories(categories)
# 添加到工作表
worksheet.add_chart(chart, "E5")
from openpyxl.formatting.rule import ColorScaleRule, CellIsRule
# 色阶格式
worksheet.conditional_formatting.add(
'B2:B100',
ColorScaleRule(start_type='min', start_color='FF6347',
mid_type='percentile', mid_value=50, mid_color='FFFF00',
end_type='max', end_color='90EE90')
)
# 基于规则的格式
red_fill = PatternFill(start_color='FFC7CE', end_color='FFC7CE', fill_type='solid')
worksheet.conditional_formatting.add(
'C2:C100',
CellIsRule(operator='lessThan', formula=['0'], fill=red_fill)
)
from openpyxl.worksheet.datavalidation import DataValidation
# 下拉列表
dv = DataValidation(type="list", formula1='"优秀,良好,一般,较差"', allow_blank=True)
worksheet.add_data_validation(dv)
dv.add('D2:D100')
# 添加求和公式
worksheet['B11'] = '=SUM(B2:B10)'
# 添加平均值公式
worksheet['C11'] = '=AVERAGE(C2:C10)'
openpyxl 的 write_only 模式xlsxwriter 引擎处理复杂图表和格式try:
df = pd.read_csv('data.csv')
except FileNotFoundError:
print("数据文件不存在")
except pd.errors.EmptyDataError:
print("数据文件为空")
from datetime import datetime
# 使用时间戳避免文件覆盖
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
filename = f'sales_report_{timestamp}.xlsx'
# 检查必需列
required_columns = ['date', 'product', 'sales']
if not all(col in df.columns for col in required_columns):
raise ValueError(f"缺少必需列: {required_columns}")
# 数据类型验证
df['date'] = pd.to_datetime(df['date'])
df['sales'] = pd.to_numeric(df['sales'], errors='coerce')
~/.claude/skills/excel-report-generator/templates/ 目录templates/monthly_report.xlsx查看 examples/quick_reference.py 获取常用代码片段,包括:
examples/basic_report.py - 基础报表生成示例examples/advanced_report.py - 高级功能示例examples/template_fill.py - 模板填充示例templates/business_report.xlsx - 业务报告模板templates/data_analysis.xlsx - 数据分析模板确保已安装必需的 Python 包:
pip install pandas openpyxl xlsxwriter
可选依赖:
pip install matplotlib seaborn # 用于数据可视化
pip install sqlalchemy pymysql # 用于数据库连接
Q: 生成的 Excel 文件无法打开
A: 确保使用 .xlsx 扩展名,检查文件权限,验证数据中没有非法字符
Q: 图表不显示 A: 检查数据引用范围是否正确,确保数据类型为数值型
Q: 中文乱码
A: 使用 encoding='utf-8-sig' 读取 CSV,或在 Excel 中使用 UTF-8 编码
Q: 大文件生成很慢
A: 使用 write_only=True 模式,减少格式化操作,分批写入数据
REFERENCE.md 获取详细 API 参考xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience