关于 data-export
用于在 Node.js 和 Python 应用中实现数据导出及 CSV 解析的实用技能,涵盖大型数据集流式处理、电子表格生成、下载响应头和生产环境检查。
主要功能
- 01在 Node.js 中流式导出 CSV
- 02使用 ExcelJS 生成 Excel 工作簿
- 03流式生成大型 Excel 文件
- 04使用 Papa Parse 解析上传的 CSV
- 05使用 openpyxl 在 Python 中创建 Excel 文件
- 06应用导出安全与生产环境检查
适用场景
- 01将数据库记录导出为可下载的 CSV
- 02根据应用数据生成 Excel 报告
- 03在前端解析上传的 CSV 文件
- 04处理大型导出,避免将全部数据载入内存
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ claude-dev-suite/ claude-dev-suite --skill data-export安装后在 Claude Code 中输入/data-export确认已加载。
详细介绍
数据导出
CSV 导出(Node.js)
import { stringify } from 'csv-stringify';
import { pipeline } from 'stream/promises';
// Streaming CSV (handles large datasets)
app.get('/api/export/users.csv', async (req, res) => {
res.setHeader('Content-Type', 'text/csv');
res.setHeader('Content-Disposition', 'attachment; filename="users.csv"');
const cursor = db.collection('users').find().cursor();
const csvStringifier = stringify({
header: true,
columns: ['name', 'email', 'createdAt'],
});
await pipeline(cursor, csvStringifier, res);
});
// Simple in-memory CSV
import { stringify } from 'csv-stringify/sync';
const csv = stringify(rows, { header: true, columns: ['name', 'email', 'amount'] });
Excel 导出(ExcelJS — 推荐)
import ExcelJS from 'exceljs';
app.get('/api/export/report.xlsx', async (req, res) => {
const workbook = new ExcelJS.Workbook();
const sheet = workbook.addWorksheet('Report');
// Headers with styling
sheet.columns = [
{ header: 'Name', key: 'name', width: 25 },
{ header: 'Email', key: 'email', width: 30 },
{ header: 'Amount', key: 'amount', width: 15 },
];
sheet.getRow(1).font = { bold: true };
// Data
const users = await getUsers();
users.forEach((u) => sheet.addRow(u));
// Number formatting
sheet.getColumn('amount').numFmt = '$#,##0.00';
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', 'attachment; filename="report.xlsx"');
await workbook.xlsx.write(res);
});
大型数据集的流式 Excel 导出
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ stream: res });
const sheet = workbook.addWorksheet('Data');
sheet.columns = [{ header: 'Name', key: 'name' }, { header: 'Value', key: 'value' }];
for await (const row of cursor) {
sheet.addRow(row).commit(); // Flushes row to stream
}
await workbook.commit();
前端 CSV 解析(Papa Parse)
import Papa from 'papaparse';
// Parse uploaded CSV
const result = Papa.parse<UserRow>(file, {
header: true,
skipEmptyLines: true,
dynamicTyping: true,
complete: (results) => {
console.log(results.data); // Parsed rows
console.log(results.errors); // Parse errors
},
});
// Generate CSV in browser
const csv = Papa.unparse(data);
const blob = new Blob([csv], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
Python(openpyxl)
from openpyxl import Workbook
from io import BytesIO
def export_excel(data: list[dict]) -> bytes:
wb = Workbook()
ws = wb.active
ws.title = "Report"
headers = list(data[0].keys())
ws.append(headers)
for row in data:
ws.append([row[h] for h in headers])
buffer = BytesIO()
wb.save(buffer)
return buffer.getvalue()
反模式
| 反模式 | 修复方法 |
|---|---|
| 将所有数据加载到内存中 | 对于大型导出,从数据库游标读取数据流 |
| 未设置 Content-Disposition 标头 | 始终设置该标头以供浏览器下载 |
| 在请求处理程序中生成导出文件 | 对于超过 10K 行的数据,使用后台任务 |
| 没有进度提示 | 使用 WebSocket/SSE 显示大型导出的进度 |
| CSV 值未转义 | 使用库(csv-stringify、Papa Parse) |
生产环境检查清单
- 对超过 10K 行的数据集使用流式处理
- 为大型导出配置后台任务队列
- 设置正确的 Content-Type 和 Content-Disposition 标头
- 监控内存限制
- 对导出端点进行速率限制
- 如果写入磁盘,则清理临时文件
评论
支持 Markdown