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 "";

}

}

}

相关推荐
黑科技工坊几秒前
2026年口碑载道:铝面板定制供应商优选指南
大数据·人工智能·python
ai小陈5 分钟前
PyTorch实验可复现实战:随机种子、依赖锁定与配置归档
人工智能·pytorch·python·深度学习·ai·gpu算力
郝学胜-神的一滴6 分钟前
C++11 工程级应用 08:Lambda表达式与Tuple元组
开发语言·jvm·c++·python·程序人生·开源
岁月宁静14 分钟前
三、《从零手撸 Agent》 · system prompt 与核心参数:调好你的旋钮
后端·python·agent
卷无止境17 分钟前
除了写代码,AI智能体还能帮开发者做什么
人工智能·python
我不会起名字32222 分钟前
一天一道算法题(26):栈的简单应用
java·数据结构·python·算法·leetcode·golang·
爱吃苹果的梨叔26 分钟前
AI 算力监控中心怎么建?分布式坐席 + 大屏联动 + 过程回放
人工智能·分布式·python
JarmanYuo27 分钟前
YOLO 涨点研究(六):网络结构改进之小目标增强篇1——无人机视角下的车辆与行人检测
人工智能·pytorch·python·yolo·计算机视觉·无人机
2601_9622972532 分钟前
python自带缓存lru_cache用法及扩展的使用_python
python·缓存·装饰器·lru_cache·my_cache