小代码审查|从Excel到Json Node JS

时间:2019-06-10 09:28:48

标签: javascript node.js json excel

简介->我必须转换一个excel文件,通常以这种方式出现:

enter image description here

到必须如下所示的Json文件:

"DE": {
   "Title":"Title_DE",
   "Subtitle":"Subtitle_DE",
   "Title_2":"Title_2_DE",
   "Subtitle_2":"Subtitle_2_DE"
}
"GR": {
   "Title":"Title_GR",
   "Subtitle":"Subtitle_GR",
   "Title_2":"Title_2_GR",
   "Subtitle_2":"Subtitle_2_GR"
}
"EN": {
   "Title":"Title_EN",
   "Subtitle":"Subtitle_EN",
   "Title_2":"Title_2_EN",
   "Subtitle_2":"Subtitle_2_EN"
}

我所做的->我已使用此节点模块xlsx来解析excel文件。该代码当前有效,但是我心中告诉我,这不是最好的方法,或者至少有一种最清晰或最聪明的方法。

const XLSX = require('xlsx');
const fs = require('fs');
let workbook = XLSX.readFile('./src/xls/test.xlsx'); 
let sheet_name_list = workbook.SheetNames; //--> sheet names
let isocodes = [];
let labels = [];
let copy = [];
let obj = {};
let j = 0;

sheet_name_list.map(sheet => { //--> sheet names loop
    let worksheet = workbook.Sheets[sheet]; 
    for (index in worksheet) {
        let idCol = index.substring(1, 3);
        let idRow = index.substring(0, 1);
        if (idCol === "1") {
            isocodes.push((worksheet[index].v).trim()); //--> isocodes
        }
        if (idRow === "A") {
            labels.push((worksheet[index].v).trim()); //--> labels
        }
        if (idRow != "A" && idCol != "1") {
            copy.push(worksheet[index].v); //--> copy
        }
    }
});

isocodes.shift(); //--> delete undefined
labels.shift();
copy.shift();

isocodes.map(iso => { //--> create object to convert
    obj[iso] = {};
    for (let i = 0; i < labels.length; i++) {
        obj[iso][labels[i]] = copy[(i * isocodes.length) + j];
    }
    j++;
});
//--> write json files in their folder
fs.writeFile('src/lang/desktop.json', JSON.stringify(obj).replace(/\\n|\\r/g, ''), 'utf8', console.log("desktop json file created"));
fs.writeFile('src/lang/mobile.json', JSON.stringify(obj).replace(/\\n|\\r/g, ''), 'utf8', console.log("mobile json file created"));

请分享您的想法!!!

0 个答案:

没有答案