name: exceljs description: 在Node.js中读取、操作和写入Excel电子表格(XLSX)。完全支持样式、公式、图表和大文件流式处理。 metadata: short-description: Excel电子表格操作 source: repository: https://github.com/exceljs/exceljs license: MIT stars: 14k+
ExcelJS 工具
描述
读取、操作和写入Excel电子表格,完全支持格式设置。
来源
- 代码库: exceljs/exceljs
- 许可证: MIT
安装
npm install exceljs
使用示例
创建Excel文件
import ExcelJS from 'exceljs';
async function createReport() {
const workbook = new ExcelJS.Workbook();
workbook.creator = '我的应用';
workbook.created = new Date();
const sheet = workbook.addWorksheet('销售报告');
// 定义列
sheet.columns = [
{ header: 'ID', key: 'id', width: 10 },
{ header: '产品', key: 'product', width: 30 },
{ header: '数量', key: 'quantity', width: 15 },
{ header: '价格', key: 'price', width: 15 },
{ header: '总计', key: 'total', width: 15 },
];
// 添加数据
const data = [
{ id: 1, product: '部件A', quantity: 100, price: 9.99 },
{ id: 2, product: '部件B', quantity: 50, price: 19.99 },
{ id: 3, product: '部件C', quantity: 75, price: 14.99 },
];
data.forEach(item => {
sheet.addRow({
...item,
total: { formula: `C${sheet.rowCount + 1}*D${sheet.rowCount + 1}` },
});
});
await workbook.xlsx.writeFile('report.xlsx');
}
样式化单元格
async function createStyledReport() {
const workbook = new ExcelJS.Workbook();
const sheet = workbook.addWorksheet('样式化');
// 带样式的标题行
const headerRow = sheet.addRow(['姓名', '邮箱', '状态']);
headerRow.eachCell(cell => {
cell.fill = {
type: 'pattern',
pattern: 'solid',
fgColor: { argb: '4F46E5' },
};
cell.font = { color: { argb: 'FFFFFF' }, bold: true };
cell.alignment = { horizontal: 'center' };
cell.border = {
top: { style: 'thin' },
bottom: { style: 'thin' },
};
});
// 数据行
const users = [
{ name: '张三', email: 'john@example.com', status: '活跃' },
{ name: '李四', email: 'jane@example.com', status: '非活跃' },
];
users.forEach(user => {
const row = sheet.addRow([user.name, user.email, user.status]);
// 条件格式
const statusCell = row.getCell(3);
statusCell.fill = {
type: 'pattern',
pattern: 'solid',
fgColor: { argb: user.status === '活跃' ? '22C55E' : 'EF4444' },
};
});
await workbook.xlsx.writeFile('styled-report.xlsx');
}
读取Excel文件
async function readExcel(filePath: string) {
const workbook = new ExcelJS.Workbook();
await workbook.xlsx.readFile(filePath);
const sheet = workbook.getWorksheet('Sheet1');
const data: any[] = [];
sheet?.eachRow((row, rowNumber) => {
if (rowNumber === 1) return; // 跳过标题行
data.push({
id: row.getCell(1).value,
name: row.getCell(2).value,
email: row.getCell(3).value,
});
});
return data;
}
流式处理大文件
async function streamLargeExcel(data: any[], outputPath: string) {
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
filename: outputPath,
useStyles: true,
});
const sheet = workbook.addWorksheet('数据');
sheet.columns = [
{ header: 'ID', key: 'id' },
{ header: '数值', key: 'value' },
];
// 流式写入行(内存高效)
for (const item of data) {
sheet.addRow(item).commit();
}
await workbook.commit();
}
标签
excel, spreadsheet, xlsx, report, data-export
兼容性
- Codex: ✅
- Claude Code: ✅