//node-xlsx.js [ 建议复制代码 粘贴成.js文件看]
var nodeXlsx = require('node-xlsx');
var fs = require('fs');
var sheet = []; //表头
var data = []
var item = 'armor';
var fn = './dataConfig/'+item+'.json';
var readJson = function(filename,cb){
var result;
fs.exists(filename, function(exists) {
if (exists) {
fs.readFile(filename, function(err, data) {
if (err) {
cb();
} else{
result = JSON.parse(data);
cb(result);
}
});
} else {
cb();
}
});
}
readJson(fn,function(data){
if(!!data && data.length > 0){
if(!sheet[item]){
sheet[item] = {sheet : [],value :[]};
}
var first = data[0];
for(var key in first){
sheet[item].sheet.push(key);
}
for(var i = 0;i < data.length;i++){
var value = data[i];
for(var key in value){
if(!sheet[item].value[i]){
sheet[item].value[i] = [];
}
sheet[item].value[i].push(value[key]);
}
}
}
sheet[item].value.unshift(sheet[item].sheet);
var fileSheet = sheet[item].value;
console.log('fileSheet:',fileSheet);
var resultFN = './xlsx/'+item+'.xlsx';
if (fs.existsSync(resultFN)) {
fs.unlinkSync(resultFN);
}
var obj = {"worksheets": [
{"data": fileSheet}
]};
var file = nodeXlsx.build(obj);
fs.writeFile(resultFN, file, 'binary', function (err) {
if (!err){
console.log('保存文件成功!');
} else {
console.log(err);
}
});
});