当前的目录结构
excel的数据如下:
node识别excel,先得安装 node-xlsx,用npm或yarn都可以
npm install node-xlsx
或
yarn add node-xlsx
index.js 完整代码如下:
const fs = require('fs');
const xlsx = require('node-xlsx')
// excel数据
const excelData = xlsx.parse('./excel/students.xlsx');
// 最终数据
let finalArr = [];function handelExcel() {
// excel的第一个sheet
const excelSheet = excelData[0].data;
// 表头
const columns = excelSheet[0];
// 表头对应的key
const columnsObj = {
username: '姓名',
age: '年龄',
gender: '性别',
score: '分数'
}
let JSONKey = []
// 设置JSON key值
columns.forEach(item => {
for (key in columnsObj) {
const itemKey = columnsObj[key];
itemKey === item ? JSONKey.push(key) : ''
}
})
// 表内容
const jsonData = excelSheet.slice(1);
jsonData.forEach(lineItem => {
let arrItem = {}
lineItem.forEach((item, index) => Object.assign(arrItem, { [JSONKey[index]]: item }))
finalArr.push(arrItem);
})
};handelExcel();
generatJSON('./data/data.json', JSON.stringify(finalArr, null , '\t'))/**
* 生成JSON文件
* @param {*} fileName
* @param {*} data
*/
function generatJSON(fileName, data) {
fs.writeFile(fileName, data, 'utf-8', function (err) {
if (err) {
console.log('errr');
} else {
console.log('success');
}
})
}
最后执行 node index.js 即可生成文件