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

}

}

}

相关推荐
高洁0130 分钟前
世界模型的因果内核:从预测表象到理解机制
人工智能·python·深度学习·transformer·迁移学习
数字融合1 小时前
透明化视频动态三维重建空间数据零核心技术
人工智能·python·virtualenv
AI创界者1 小时前
Python 进阶实战(五十四章):大模型推理网关终极架构——分布式全局前缀 Trie 缓存同步与多网关高可用协同调度
人工智能·python·aigc
萧子琦2 小时前
零第三方依赖能做到什么程度?开源两个纯标准库安全小工具:StarShield Forensics 与澄镜 ClearLens
python
用户91294046848422 小时前
Codex 从零到能交付(19):让 Codex 做代码审查:发现问题后怎样验证
python
小白勇闯网安圈2 小时前
day_2
python
叮当小飞鱼2 小时前
RAG幻觉
python
赵大仁3 小时前
Agent 工具调用可靠性:超时、重试、幂等与人工确认怎么设计
python·agent·幂等·工具调用·人工确认
__underline__4 小时前
冷门Python知识点007篇:list[int]不是类,为什么能当基类?
后端·python
Dmz丶4 小时前
前端转 AI 100 天 Day 49:文档切分——RAG 效果的隐形开关
python