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

}

}

}

相关推荐
kkoral16 分钟前
如何在 Python 中使用 OpenCV 调用 FFmpeg 的特定功能?
python·opencv·ffmpeg
樹JUMP18 分钟前
Python虚拟环境(venv)完全指南:隔离项目依赖
jvm·数据库·python
free_7320 分钟前
超越“回答”,AI Agent迎来全链路安全治理挑战
人工智能·python·网络安全
sg_knight21 分钟前
设计模式实战:策略模式(Strategy)
java·开发语言·python·设计模式·重构·架构·策略模式
飞Link29 分钟前
告别 ROS 的臃肿:用 ZeroMQ 构建极速具身智能分布式大脑(附 Python 实战)
开发语言·分布式·python
嫂子的姐夫32 分钟前
039-DES:gov招标(解密)
爬虫·python·js逆向·逆向
jgyzl35 分钟前
2026.3.20 用EasyExcel实现excel报表的导入与导出
java·python·excel
weixin_4331793343 分钟前
python - 正则表达式Regex
python·正则表达式
Riemann~~1 小时前
ros2写一个可以修改参数的node
开发语言·python·ros2·机器人系统
郝学胜-神的一滴1 小时前
PyTorch 张量基础:零张量/一张量/指定值张量全解析
人工智能·pytorch·python