feat(tools): 添加 JSON 转 Excel 功能
- 新增 json2excel.js 工具脚本,用于将 JSON 数据转换为 Excel 文件 - 在 package.json 中添加 xlsx 依赖 - 使用 SpecialRingConfig.json 作为示例进行转换并生成 SpecialRingConfig.xlsx 文件
This commit is contained in:
BIN
excels/SpecialRingConfig.xlsx
Normal file
BIN
excels/SpecialRingConfig.xlsx
Normal file
Binary file not shown.
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"dependencies": {
|
||||
"jszip": "^3.10.1"
|
||||
"jszip": "^3.10.1",
|
||||
"xlsx": "^0.18.5"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "node build.js",
|
||||
|
||||
54
tools/json2excel.js
Normal file
54
tools/json2excel.js
Normal file
@@ -0,0 +1,54 @@
|
||||
const XLSX = require("xlsx");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { json } = require("stream/consumers");
|
||||
const { log } = require("console");
|
||||
const folderPath = "./configs";
|
||||
const scope = [
|
||||
"SpecialRingConfig",
|
||||
// "StdItems",
|
||||
// "Monster",
|
||||
// "ItemMergeConfig",
|
||||
// "MergeConfig",
|
||||
// "NpcTransConf"
|
||||
// "MergeTotal", "RecyclingSettingConfig", "UpstarConfig",
|
||||
].filter(Boolean);
|
||||
|
||||
function handleJson2ArrayJson(jsonData) {
|
||||
const arr = [];
|
||||
const findElement = (obj) => {
|
||||
for (const key in obj) {
|
||||
if (isNaN(key) && Object.hasOwnProperty.call(obj, key)) {
|
||||
if(typeof obj[key] === "object")
|
||||
obj[key] = JSON.stringify(obj[key]);
|
||||
} else if (typeof obj[key] === "object") {
|
||||
findElement(obj[key]);
|
||||
}
|
||||
}
|
||||
arr.push(obj);
|
||||
};
|
||||
findElement(jsonData);
|
||||
return arr;
|
||||
}
|
||||
function json2excel(jsonData, fileName) {
|
||||
if (!Array.isArray(jsonData)) jsonData = Object.values(jsonData);
|
||||
const data = handleJson2ArrayJson(jsonData)?.filter(Boolean);
|
||||
|
||||
const workbook = XLSX.utils.book_new();
|
||||
const worksheet = XLSX.utils.json_to_sheet(data);
|
||||
XLSX.utils.book_append_sheet(workbook, worksheet, fileName);
|
||||
XLSX.writeFile(workbook, `./excels/${fileName}.xlsx`);
|
||||
}
|
||||
|
||||
const start = () => {
|
||||
const files = fs.readdirSync(folderPath);
|
||||
|
||||
// 过滤出所有的 JSON 文件
|
||||
const jsonFiles = files.filter((file) => path.extname(file) === ".json").filter((file) => scope.map((e) => `${e}.json`).includes(file));
|
||||
jsonFiles.forEach((file) => {
|
||||
const json = JSON.parse(fs.readFileSync(path.join(folderPath, file), "utf8"));
|
||||
const filename = path.basename(file, path.extname(file));
|
||||
json2excel(json, filename);
|
||||
});
|
||||
};
|
||||
start();
|
||||
Reference in New Issue
Block a user