说在前面
比如我们现在有这么一个excel数据表:
我们需要将其转为json数据,并按地市进行分组:
1、导入模块
- 首先,通过
require
导入了xlsx
和fs
模块。xlsx
模块用于操作excel文件,fs
模块用于文件系统操作(如读取和写入文件)。
2、读取excel文件
- 使用
xlsx.readfile
函数读取指定路径("./file/地市区县.xlsx"
)下的excel文件,并将结果存储在workbook
变量中。
const workbook = xlsx.readfile("./file/地市区县.xlsx");
3、获取工作表数据并转换为json
- 从
workbook
中获取名为sheet1
的工作表,并将其存储在变量sheet
中。 - 然后使用
xlsx.utils.sheet_to_json
函数将工作表数据转换为json格式,并存储在sheetjson
变量中。
const sheet = workbook.sheets["sheet1"]; const sheetjson = xlsx.utils.sheet_to_json(sheet);
获取到的json数据如下:
4、构建地区映射对象
- 获取到excel的json数据之后,我们还需要对数据进行处理,将同一地市的区县归并起来。
- 遍历
sheetjson
中的每一项。对于每一项,检查respoolmap
对象中是否已经存在对应的地市键。如果不存在,则创建一个空数组作为该地市的值;如果存在,则获取该数组。 - 将当前项的区县值添加到对应地市的数组中,并更新
respoolmap
对象。
const respoolmap = {}; sheetjson.foreach((item) => { const list = respoolmap[item.地市] || []; list.push(item.区县); respoolmap[item.地市] = list; });
5、写入json文件
- 使用
fs.writefilesync
函数将respoolmap
对象转换为格式化的json字符串(通过json.stringify(respoolmap,null, 2)
),并写入到"./file/地市区县.json"
文件中。
fs.writefilesync(`./file/地市区县.json`, json.stringify(respoolmap,null, 2));
总体来说,就是通过xlsx读取一个excel文件中的数据。然后将数据重新组织,以地市为键,其下属的区县列表为值,构建一个对象。最后将这个对象保存为一个json文件。
完整代码
const xlsx = require("xlsx"); const fs = require("fs"); const workbook = xlsx.readfile("./file/地市区县.xlsx"); const sheet = workbook.sheets["sheet1"]; const sheetjson = xlsx.utils.sheet_to_json(sheet); const respoolmap = {}; sheetjson.foreach((item) => { const list = respoolmap[item.地市] || []; list.push(item.区县); respoolmap[item.地市] = list; }); fs.writefilesync(`./file/地市区县.json`, json.stringify(respoolmap, null, 2));
这是一个读取excel数据并转换为json的简单脚本,大家可以根据自己的需求进行微调使用
到此这篇关于node将excel数据转为json的示例代码的文章就介绍到这了,更多相关node excel数据转json内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论