ExcelToJson

import org.apache.poi.ss.usermodel.*;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.json.JSONArray;

import org.json.JSONObject;

import java.io.FileInputStream;

import java.util.HashMap;

import java.util.Map;

public class ExcelToJson {

public static void main(String\[\] args) {

String excelFilePath = "zzz.xlsx";

Map<String, JSONArray> dataMap = new HashMap<>();

try (FileInputStream fis = new FileInputStream(excelFilePath);

Workbook workbook = new XSSFWorkbook(fis)) {

Sheet sheet = workbook.getSheetAt(1);

Row headerRow = sheet.getRow(0);

for (Row row : sheet) {

if (row.getRowNum() == 0) {

continue; //Policy.RETURN_BLANK_AS_NULL);

}

Cell keyCell = row.getCell(0, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);

if (keyCell == null) {

continue; // Skip rows where the key cell is empty

}

String key = getCellValue(keyCell).toString();

JSONArray jsonArray = dataMap.getOrDefault(key, new JSONArray());

JSONObject jsonObject = new JSONObject();

for (int cn = 1; cn < row.getLastCellNum(); cn++) {

Cell cell = row.getCell(cn, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);

if (cell != null) {

String header = headerRow.getCell(cn).getStringCellValue();

jsonObject.put(header, getCellValue(cell));

}

}

jsonArray.put(jsonObject);

dataMap.put(key, jsonArray);

}

// Print the JSON output

dataMap.forEach((key, value) -> System.out.println(key + ": " + value.toString()));

} catch (Exception e) {

e.printStackTrace();

}

}

private static Object getCellValue(Cell cell) {

switch (cell.getCellType()) {

case STRING:

return cell.getStringCellValue();

case NUMERIC:

return cell.getNumericCellValue();

case BOOLEAN:

return cell.getBooleanCellValue();

default:

return "";

}

}

}

相关推荐
梅雅达编程笔记1 小时前
编程启蒙|Scratch 转 Python 系列第9天:字典/哈希表积木双向对照(AI大模型参数配置表实战)
开发语言·人工智能·python·numpy·pandas
zhz52142 小时前
GIS项目中空间参考转换与MBTiles偏移:问题成因、解法与避坑
python·vue·gis
KaMeidebaby3 小时前
卡梅德生物技术快报|如何制备单克隆抗体:小众禽类靶点单抗制备实操流程:双载体抗原交叉筛选完整工艺记录
人工智能·python·深度学习·算法·机器学习
乱写代码3 小时前
Pydantic学习--BaseModel
python
fu15935745683 小时前
【边缘计算实战】P1:从零搭建边云任务卸载仿真实验台(Python 可复现)
数据库·python·边缘计算
蜡台4 小时前
通过Gradle脚本声明更改Java变量
android·java·开发语言·python·kotlin·gradle·groovy
智能体与具身智能5 小时前
TVA 本质内涵与核心特征(系列)
人工智能·python·智能体视觉
云雾J视界5 小时前
SST:高频变压器设计实战:铁氧体 vs 纳米晶 vs 非晶,磁性材料怎么选
python·acdc·dab·sst
第一程序员5 小时前
Rust trait 入门:把 AI 客户端抽象成可替换接口
python·rust·github
Ulyanov5 小时前
Python实现6-DOF刚体仿真器(下)——环境扰动与控制闭环
开发语言·python·算法·系统仿真·雷达电子对抗·导引头