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

}

}

}

相关推荐
去码头整点薯条ing1 分钟前
某红书笔记接口逆向【x-s参数】
javascript·爬虫·python
xxie1237943 分钟前
参数Parameter,形参Formal Parameter,实参Actual Argument
开发语言·python
love530love4 分钟前
Hermes-Agent 本地化部署与详细交互式配置实战指南 [LM Studio + QQ ]
人工智能·windows·python·aigc·agent·hermes·hermes-agent
高洁016 分钟前
人人可用的智能体来了
python·深度学习·机器学习·数据挖掘·知识图谱
装不满的克莱因瓶7 分钟前
NLP中的卷积神经网络CNN——从图像卷积到文本特征提取的跨界应用
人工智能·pytorch·python·深度学习·神经网络·自然语言处理·cnn
在放️10 分钟前
Python 爬虫 · XML、xpath 与 lxml 模块基础
开发语言·爬虫·python
挨踢诗人16 分钟前
天猫(淘宝开放平台)集成金蝶云星空
python·数据集成
xyz_CDragon24 分钟前
把旧电脑变成AI算力:llama.cpp RPC 局域网分布式推理验证与实战
人工智能·分布式·python·rpc·llama
lulu121654407826 分钟前
GPT-5.6 vs Claude Fable 5/Mythos 深度技术对比:kindle/kepler/Levi三版本实测全解析
java·人工智能·python·gpt
喵叔哟28 分钟前
Week 3 --Day 2:LangGraph 进阶
python·langchain