使用nodejs/exceljs读取、操作、写入excel文件
const ExcelJS = require('exceljs');
// 异步读取Excel文件
async function readExcel(filePath) {
const workbook = new ExcelJS.Workbook();
await workbook.xlsx.readFile(filePath);
const worksheet = workbook.getWorksheet(1);
worksheet.eachRow({ includeEmpty: true }, function(row, rowNumber) {
console.log("Row " + rowNumber + " = " + JSON.stringify(row.values));
});
}
// 异步写入Excel文件
async function writeExcel(filePath) {
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('My Sheet');
worksheet.columns = [
{ header: '姓名', key: 'name' },
{ header: '年龄', key: 'age' },
{ header: '职业', key: 'occupation' }
];
worksheet.addRow({ name: 'John Doe', age: 30, occupation: 'Developer' });
worksheet.addRow({ name: 'Jane Doe', age: 25, occupation: 'Designer' });
await workbook.xlsx.writeFile(filePath);
}
// 使用方法
const filePath = './example.xlsx';
readExcel(filePath).then(() => {
console.log('Excel文件读取完毕');
});
writeExcel(filePath).then(() => {
console.log('Excel文件写入完毕');
});
这段代码展示了如何使用exceljs
库来异步读取和写入Excel文件。readExcel
函数打开一个Excel文件并遍历每一行,writeExcel
函数创建一个新的Excel文件,定义了列的头部并添加了几行数据。这些操作都是异步的,不会阻塞事件循环,适合处理大量数据的场景。
评论已关闭