var xlsx = require('node-xlsx');
var obj = xlsx.parse(__dirname + '/myFile.xlsx'); // parses a file
下面是一段样例代码:
12345678910111213141516171819202122
// Include modules.
var xlsx = require('node-xlsx');
// read xlsx file and analyse
var excelObj = xlsx.parse('fileName.xlsx');
for (var sheet in excelObj) {
if (sheet !== '0' && excelObj.hasOwnProperty(sheet)) { // sheet is '0', '1', ...
var sheetData = excelObj[sheet].data; // data inside a sheet, which is an two-dimention array
var rowCount = sheetData.length;
activityCountDic[sheet] = rowCount;
for (var i = 1; i < rowCount; i++) {
var rowData = sheetData[i]; // data inside one row, which is an one-dimention array
var columnCount = rowData.length;
for (var j = 0; j < columnCount; j++) {
var cellData = rowData[j].toString(); // data in j column of the given row
console.log(cellData);
}
}
}
}
写入excel文件
123456789101112131415161718192021222324252627
// Include modules.
var xlsx = require('node-xlsx');
var fs = require('fs');
// 写入excel之后是一个一行两列的表格
var data1 = [
['name', 'age']
];
// 写入excel之后是一个三行两列的表格
var data2 = [
['name', 'age'],
['zhang san', '10'],
['li si', '11']
];
var buffer = xlsx.build([
{
name:'sheet1',
data:data1
}, {
name:'sheet2',
data:data2
}
]);
fs.writeFileSync('book.xlsx', buffer, {'flag':'w'}); // 如果文件存在,覆盖
运行
将上面的代码保存成js文件,比如demo.js,通过node运行即可:
1
node demo.js
如果需要debug,可以使用VSCode。在开始运行的时候碰到下面的错误“Cannot find runtime ‘node’ on PATH. Is ‘node’ installed?”。需要将自动生成的launch.json文件添加一行: