nodejs实现读写excel文件操作

栏目: NodeJs 发布时间:2021-12-24

安装依赖

yarn add node-xlsx

读 excel

  • 方法一:parse buffer
const xlsx = require('node-xlsx').default
const fs = require('fs')
const workSheetsFromBuffer = xlsx.parse(fs.readFileSync(`./excels/1.xls`));
const firstSheetData = workSheetsFromBuffer[0].data
console.log(firstSheetData[0]) // [ '应用:xxx' ]
console.log(firstSheetData[1]) // []
console.log(firstSheetData[2]) // [ '页面url', '访问次数', '访问人数', '打开次数', '独立IP数', '平均在线时长' ]
console.log(firstSheetData[3]) // ['views/pages/index/index', 238617, 102431, 152730, 95439, 0.0009027777777777777]
  • 方法二:parse file
    const xlsx = require('node-xlsx').default
    const workSheetsFromFile = xlsx.parse(`./excels/1.xls`);
    const firstSheetData = workSheetsFromFile[0].data
    console.log(firstSheetData[0]) // [ '应用:xxx' ]
    console.log(firstSheetData[1]) // []
    console.log(firstSheetData[2]) // [ '页面url', '访问次数', '访问人数', '打开次数', '独立IP数', '平均在线时长' ]
    console.log(firstSheetData[3]) // ['views/pages/index/index', 238617, 102431, 152730, 95439, 0.0009027777777777777]
    

写 excel

const fs = require('fs')
const xlsx = require('node-xlsx').default
const data = [
  ['姓名', 'age'],
  ['lucy', '18'],
  ['tom', '16']
]
const options = {}
const excelBuffer = xlsx.build([{
  name: 'mySheetName',
  data: data 
}], options)
fs.writeFileSync('./output-demo.xls', excelBuffer)
console.log('done!', './output-demo.xls')

本文地址:https://www.tides.cn/p_node-read-and-write-excel

标签: node excel node-xlsx