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

}

}

}

相关推荐
飞猪~38 分钟前
LangChain python 版本 第一集
开发语言·python·langchain
2601_956319881 小时前
最新AI量化提效,先做可验证的小流程
人工智能·python
开飞机的舒克_3 小时前
FastAPI 实战入门:从路由、参数校验到依赖注入的后端开发指南
python·fastapi
霸道流氓气质3 小时前
Kiro 中反编译 JAR 包并分析字节码的流程指南
chrome·python·jar
人工智能时代 准备好了吗3 小时前
AI回答内容进入率监测:引用识别、文本匹配与语义判断
开发语言·人工智能·python
Metaphor6924 小时前
使用 Python 冻结 Excel 文件中的行、列和单元格
开发语言·python·excel
言乐64 小时前
Python实现建造微服务商城后台
开发语言·python·算法·微服务·架构
fenglllle5 小时前
chromadb emmbedding 向量检索
人工智能·python·embedding
cui_ruicheng5 小时前
Python从入门到实战(六):非序列容器
开发语言·python
百里香酚兰5 小时前
【python学习笔记】pyttsx3库疑似只播报一次语音
笔记·python·学习