

使用 node-excel-stream 来按行处理 Excel 数据
source link: https://www.ixiqin.com/2022/08/03/use-the-node-excel-to-press-line-processing-excel-data-stream/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.


使用 node-excel-stream 来按行处理 Excel 数据
数据分析是一个非常常见的需求,而在实际的落地场景当中, Python 是使用最多的。不过我因为写了很久的前端,其实对于Python已经生疏了。当我开始启动项目时,就会选择执行 npm init
来初始化一个项目。既然如此,就试着使用 Node.js 来做数据分析。
在 Node.js 当中操作 Excel ,最好的便是 Exceljs。不过 ExcelJs 封装了大量的函数,对于绝大多数的数据分析场景来说,可能并不适用(也不一定,只是我比较喜欢用代码来描述逻辑,Excel 更多是一个导入导出)。
当明确了我只是需要一个简单的导入导出后,那么 node-excel-stream 就进入了我的视野。
读取 Excel 内容
和 Exceljs 不同,node-excel-stream 的封装相对简单,就是一个 Reader 和 Writer ,提供的方法也十分简单:读取文件、定义格式,按行处理内容;
需要注意的是,node-excel-stream 只支持 xlsx ,而不支持 xls,所以如果你用的是旧版,则需要重新保存成 xlsx 来进行处理。
let dataStream = fs.createReadStream('data.xlsx');
let reader = new ExcelReader(dataStream, {
sheets: [{
name: 'Users',
rows: {
headerRow: 1,
allowedHeaders: [{
name: 'User Name',
key: 'userName'
}, {
name: 'Value',
key: 'value',
type: Number
}]
}
}]
})
console.log('starting parse');
reader.eachRow((rowData, rowNum, sheetSchema) => {
console.log(rowData);
})
.then(() => {
console.log('done parsing');
});
写入 Excel 内容
写入时和读取时相比,稍微复杂一点,需要将所有的输入使用 Promise.all
包裹起来
let writer = new ExcelWriter({
sheets: [{
name: 'Test Sheet',
key: 'tests',
headers: [{
name: 'Test Name',
key: 'name'
}, {
name: 'Test Coverage',
key: 'testValue',
default: 0
}]
}]
});
let dataPromises = inputs.map((input) => {
// 'tests' is the key of the sheet. That is used
// to add data to only the Test Sheet
writer.addData('tests', input);
});
Promise.all(dataPromises)
.then(() => {
return writer.save();
})
.then((stream) => {
stream.pipe(fs.createWriteStream('data.xlsx'));
});
如果你需要将 Excel 导入到 Js 当中进行处理,那么 node-excel-stream 是一个不错的选择。
本条目发布于2022年8月3日。属于Node.js分类,被贴了 excel、github、开发经验 标签。
← warehouse — 一个简单易用的 JSON 数据库 使用 Sheetjs 将 JSON Array 转化为 Excel →
发表回复 取消回复
您的电子邮箱地址不会被公开。 必填项已用*标注
评论 *
显示名称 *
电子邮箱地址 *
网站地址
在此浏览器中保存我的显示名称、邮箱地址和网站地址,以便下次评论时使用。
如果有人回复我的评论,请通过电子邮件通知我。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK