JSON 导出 xlsx

TIP

本案例只是一个 Demo,满足个人场景使用,经测试可以把 JSON 数据导出为 Excel 文件

具体代码逻辑需要根据实际业务进行调整

代码执行环境为 nodejs

业务场景

将代码中配置好的 JSON 数据导出生成 Excel 类型的文件

  • 翻译多语言作为源文件提供

安装

Github 地址

npm
pnpm
npm install node-xlsx --save

源数据

data.json
{
  "common": {
    "region": {
      "global": "Global",
      "china": "China",
      "russia": "Russia",
      "singapore": "Singapore",
      "th": "Thailand"
    },
    "remove": "Remove",
    "language": "Language"
  }
  // ...
}

转换方法

index.js
1const fs = require("fs");
2const xlsx = require("node-xlsx");
3
4function flattenObject(obj, prefix = "") {
5  const result = {};
6
7  for (const key in obj) {
8    if (obj.hasOwnProperty(key) && typeof obj[key] === "object" && obj[key] !== null) {
9      const newPrefix = prefix ? `${prefix}.${key}` : key;
10      Object.assign(result, flattenObject(obj[key], newPrefix));
11    } else {
12      result[prefix ? `${prefix}.${key}` : key] = obj[key];
13    }
14  }
15
16  return result;
17}
18// 转化需要时数组,['','']
19const excelDate = [["key", "en", "zh"]]; //这里就是excel的表头的值
20// 读取对应JSON文件
21const zhLangStr = fs.readFileSync("./en.json", "utf-8");
22const zhLangObj = JSON.parse(zhLangStr);
23// 英文
24const enLangStr = fs.readFileSync("./zh-CN.json", "utf-8");
25const enLangObj = JSON.parse(enLangStr);
26
27let zh = flattenObject(zhLangObj);
28let en = flattenObject(enLangObj);
29
30// 遍历他的key,然后往excelDate中push它的key和vaule['','']
31Object.keys(zh).forEach((key) => {
32  Object.keys(en).forEach((key1) => {
33    if (key == key1) {
34      excelDate.push([key, zh[key], en[key]]);
35    }
36  });
37});
38
39// 设置列宽 第一列和第二列 都是30
40const sheetOptions = { "!cols": [{ wch: 30 }, { wch: 30 }] };
41const bufferZh = xlsx.build([{ name: "Sheet1", data: excelDate }], {
42  sheetOptions,
43});
44// 导出生成文件
45fs.writeFileSync("./zh.xlsx", bufferZh, { flag: "w" });

使用

运行命令成功后,后生成zh.xlsx文件

node index.js