JS文件与Excel文件互转脚本

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);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值