JSON转Excel
1.安装json2xls插件
2.先将js文件转成json文件
3.如果js对象有嵌套,转换成点对象
// 嵌套对象展平为点对象
const flattenCN = (obj, parentKey = '') => {
if (parentKey !== '') {
parentKey += '.';
}
let res = {};
Object.keys(obj).forEach((key) => {
if (typeof obj[key] === 'object' && obj[key] !== null) {
Object.assign(res, flattenCN(obj[key], parentKey + key))
} else {
res[parentKey + key] = obj[key]
}
})
return res;
}
3.写入json文件
let cn = flattenCN(CN)
let content = JSON.stringify(cn)
let file = path.join(__dirname,'cn.json') // 路径与文件名
fs.writeFile(file,content,(err)=>{
if(err){
return console.log(err)
}
console.log('文件创建成功')
})
4.将json文件转成excel文件
fs.readFile('cn.json',(err,data)=>{
if (err) {
throw err;
}
const json = JSON.parse(data);
let jsonArray = []
for(let i in json) {
jsonArray.push({ // 创建标签
'english': i,
'chinese': json[i]
})
}
let xls = json2xls(jsonArray);
// 创建excle文件
fs.writeFileSync('./CN.xlsx', xls, 'binary');
})
Excel文件转成js文件
1.安装node-xlsx插件
2.读取xlsx,获取xlsx第一个标签栏的数据
// 读取xlsx
const sheets = xlsx.parse("CN.xlsx");
// 获取xlsx第一个标签栏的数据
const sheetData = sheets[0].data;
3.定义数据列表
// 定义数据列表
let list = {};
// 循环拼装数据
sheetData.forEach((item, index) => {
if (index == 0) {
// 去除标题栏
return;
} else {
list[item[0]]=item[1];
}
});
4.创建一个函数,处理点对象转换成嵌套对象
// key是点对象转换为嵌套对象
function deepen(obj) {
const result = {};
for (const objectPath in obj) {
const parts = objectPath.split('.');
let target = result;
while (parts.length > 1) {
const part = parts.shift();
target = target[part] = target[part] || {};
}
target[parts[0]] = obj[objectPath]
}
return result;
}
5.给json对象处理头尾,让json对象变为js格式,在后面加上module.exports导出语句
let jsonObj = deepen(list);
let cnObj = 'let CN = '+JSON.stringify(jsonObj, null, 4) + '\n' + 'module.exports = CN'
6.写入文件即可
fs.writeFileSync('CN.js',cnObj);