nodejs 使用 exceljs 库读取 execl 或写入 execl 数据后保存文件
安装库 exceljs
npm i exceljs
读取execl
const exceljs = require('exceljs')
const workbook = new exceljs.Workbook()
await workbook.xlsx.readFile('test.xlsx')
// 读取第一个工作表
const worksheet = workbook.worksheets[0]
// 遍历工作表的每一行
worksheet.eachRow((row, rowNumber) => {
console.log(`Row ${rowNumber}: ${JSON.stringify(row.values)}`)
})
写入execl
const exceljs = require('exceljs')
const fs = require('fs')
const data = [
{
name: '张',
age: 18,
height: '180cm'
},
{
name: '李',
age: 19,
height: '185cm'
}
]
;(async () => {
const workbook = new exceljs.Workbook()
const worksheet1 = workbook.addWorksheet('Sheet 1')
const worksheet2 = workbook.addWorksheet('Sheet 2')
worksheet1.addRow(['姓名', '年龄', '身高'])
data.forEach((row) => {
worksheet1.addRow(Object.values(row))
})
worksheet2.addRow(['学校', '年级', '班级'])
const title_name = 'test.xlsx'
fs.writeFileSync(title_name, '')
const excelFileStream = fs.createWriteStream(title_name)
await workbook.xlsx.write(excelFileStream)
excelFileStream.end()
})()
exceljs文档
https://github.com/exceljs/exceljs/blob/HEAD/README_zh.md