xlsx转json
const xlsx = require('node-xlsx');
const fs = require('fs');
const path = require('path');
const sourcePath = './';
const savePath = '../src/language/package';
const excelNames = ['language.xlsx'];
class Translate {
constructor() {
this.contents = {};
this.languages = [];
this.sheets = undefined;
}
parseExcel(sourcePath, excelName) {
const sheets = xlsx.parse(fs.readFileSync(path.join(__dirname, sourcePath, excelName)));
sheets.forEach(this.parseSheet.bind(this));
if (!this.sheets) {
this.sheets = sheets;
} else {
this.sheets = this.sheets.concat(sheets);
}
return this;
}
parseSheet(sheet) {
let { data, name } = sheet;
data.forEach((row, rowIndex) => {
let key;
row.forEach((col, colIndex) => {
// 第一行,文件名
if (rowIndex === 0 && colIndex !== 0) {
if (!(col in this.contents)) {
this.contents[col] = {};
this.languages.push(col);
}
}
if (rowIndex >= 1) {
if (colIndex === 0) {
key = col;
} else {
const lang = this.languages[colIndex - 1];
if (lang) {
// this.contents[lang][`${name}_${key}`] = col;
this.contents[lang][`${key}`] = col;
}
}
}
});
});
return this;
}
generatorJson(savePath) {
Object.keys(this.contents).forEach(key => {
const targetPath = path.resolve(__dirname, savePath, `${key}.json`);
fs.writeFile(targetPath, JSON.stringify(this.contents[key], null, 2), res => {
console.log(`translate ${key} success`);
});
});
}
}
const translate = new Translate();
excelNames.forEach(excelName => {
translate.parseExcel(sourcePath, excelName);
});
translate.generatorJson(savePath);
json转xlsx
const fs = require('fs');
const path = require('path');
const json2xls = require('json2xls');
const sourcePath = '../src/language/package';
const zhJson = 'zh.json';
const enJson = 'en.json';
const savePath = './';
const saveFile = 'language.xlsx';
const zh = fs.readFileSync(path.join(__dirname, sourcePath, zhJson), { encoding: 'utf8' });
const en = fs.readFileSync(path.join(__dirname, sourcePath, enJson), { encoding: 'utf8' });
const json = JSON.parse(zh);
const jsonEn = JSON.parse(en);
const jsonArray = [];
Object.keys(json).forEach(key => {
jsonArray.push({ key: key, zh: json[key], en: jsonEn[key] });
});
jsonArray.sort(function (a, b) {
if (a.key > b.key) {
return 1;
} else if (a.key < b.key) {
return -1;
} else {
return 0;
}
});
let xls = json2xls(jsonArray);
const targetPath = path.resolve(__dirname, savePath, saveFile);
fs.writeFileSync(targetPath, xls, 'binary');