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

}

}

}

相关推荐
AI创界者20 分钟前
Python 进阶实战(五十六):KV Cache 驱逐闭环反馈与 Prefill / Decode 分离协同调度
人工智能·python·aigc
2601_9679801122 分钟前
Python - 变量作用域
python·闭包·变量作用域·nonlocal·嵌套函数
山楂树の2 小时前
Python 模块、包、面向对象编程
python
青少儿编程课堂3 小时前
蓝桥杯真题解析:三维偏序的CDQ分治(全国青少年信息素养大赛与电子学会编程考级)
c++·python·算法·bfs·信息学竞赛
geovindu4 小时前
python:Lasso
开发语言·后端·python·算法
3095566665 小时前
股票数据落库前的去重与主键设计:一次 SQLite 写入实录
java·开发语言·jvm·数据库·redis·python·sqlite
CyrusYiVPP5 小时前
决策树背答案背到 24 片叶子?剪枝三刀砍回 5 片,测试集从 0.749 涨回 0.845,ML数学基础第13期
人工智能·python
用户298698530145 小时前
Python 批量处理 Word 水印:文字与图片水印的添加及移除
python·api
承渊政道5 小时前
【Python编程快速上手—让繁琐工作自动化】(字典和结构化数据:用键值对搭出棋盘和游戏背包)
python·游戏·pycharm·自动化·字典和结构化数据
Wellijohn5 小时前
让 AI 能改数据库,但不能背着你改:我给 MCP Server 装了一道审批闸
python·架构·mcp