最近要对一组数据进行处理,将json格式的数据转为excel数据,之前一直是手动处理的,实在是耗费精力时间,所以想着可不可以手动处理呢?
源json数据结构
[
{
"name": "西宁市",
"code": "630100",
"children": [
{
"name": "城东区",
"code": "630102"
},
{
"name": "城中区",
"code": "630103"
},
{
"name": "城西区",
"code": "630104"
},
{
"name": "城北区",
"code": "630105"
},
{
"name": "湟中区",
"code": "630106"
},
{
"name": "大通回族土族自治县",
"code": "630121"
},
{
"name": "湟源县",
"code": "630123"
}
]
},
{
"name": "海东市",
"code": "630200",
"children": [
{
"name": "乐都区",
"code": "630202"
},
{
"name": "平安区",
"code": "630203"
},
{
"name": "民和回族土族自治县",
"code": "630222"
},
{
"name": "互助土族自治县",
"code": "630223"
},
{
"name": "化隆回族自治县",
"code": "630224"
},
{
"name": "循化撒拉族自治县",
"code": "630225"
}
]
}
]
安装依赖
要处理数据的话,需要先安装依赖。
要处理xlsx文件,需要安装node-xlsx
要保存为文件的话,需要安装fs
pnpm i node-xlsx
pnpm i fs
"fs": "0.0.1-security",
"node-xlsx": "^0.23.0",
处理文件
首先读取我们的数据 ,然后将数据转为xlsx需要的格式,然后生成对应的xlsx文件,大功告成。
import fs from 'fs'
import xlsx from 'node-xlsx'
import list from './index.json'
var sheng = '青海省'
let xlsxObj = []
list.forEach((type) => {
var data = {
name: type.name,
data: [
['name', 'code', 'url', '百度网盘'],
],
}
type.children.forEach((type2) => {
var data2 = []
data2.push(type2.name)
data2.push(type2.code)
data.data.push(data2)
});
xlsxObj.push(data)
});
fs.writeFileSync('./json/' + sheng + '/' + sheng + '.xlsx', xlsx.build(xlsxObj), "binary");