demo 示例 (具体下载附件)
ExcelDemo.js
let path = require("path");
let fs = require("fs");
let xlsx = require('node-xlsx');
let dirPath = './excel';
let outPath = './excel/config.json';
let jsonDt = {};
function getPath(dir, file) {
return path.resolve(__dirname, dir, file);
}
//解析excel文件数据,支持 xls xlsx 格式
function parseExcel(param) {
console.log(param);
let excelDt = xlsx.parse(param);
excelDt.forEach((value, index) => {
let sheetName = value.name;
let sheetData = value.data;
let sheetDt = [];
let nameArr = sheetData.splice(0, 1)[0];
let typeArr = sheetData.splice(0, 1)[0]
sheetDt.push(nameArr);
for (let s in sheetData) {
let arr = [];
for (let t in typeArr) {
let gezi = sheetData[s][t];
switch (typeArr[t]) {
case 'int':
gezi = parseInt(gezi ? gezi : null)
break;
case 'string':
gezi = String(gezi ? gezi : null);
break;
case 'array':
gezi = JSON.parse(gezi ? gezi : null);
break;
case 'json':
gezi = JSON.parse(gezi ? `{${gezi}}` : null);
break;
}
arr.push(gezi);
}
sheetDt.push(arr);
}
let paramObj = path.parse(param);
jsonDt[`${paramObj.name}#${sheetName}`] = sheetDt;
});
}
//数据输出到json
function merger() {
let jsonStr = JSON.stringify(jsonDt);
fs.open(outPath, 'w+', (err, fd) => {
if (err) {
console.log(err);
} else {
fs.writeSync(fd, jsonStr, 0, 'utf-8');
}
});
}
function __main() {
let dir = fs.readdirSync(dirPath);
for (let file of dir) {
if (file.indexOf('.xlsx') == -1 && file.indexOf('.xls') == -1)
continue;
if (file.indexOf('~$') > -1)
continue;
let ePath = getPath(dirPath, file);
parseExcel(ePath);
}
merger();
console.log('--------------生成配置结束-------------');
}
exports.main = __main;
__main();
附件
https://download.csdn.net/download/qq_37193522/68207035https://download.csdn.net/download/qq_37193522/68207035
|