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

}

}

}

相关推荐
名字还没想好☜20 小时前
Python asyncio.Queue 实战:用生产者-消费者给爬虫/任务流限速又解耦
开发语言·爬虫·python·并发·asyncio
我命由我1234520 小时前
人脸识别 - 判断人脸是否在画面中央
java·人工智能·python·java-ee·人脸识别·android jetpack·android runtime
Black_Rock_br21 小时前
本地AI工具更新,#DSH Desktop桌面端# 正式发布迭代
人工智能·python·开源·运维开发·开源软件
gfdr521 小时前
把吃灰的电视盒子,改成一台不花月租的监控
python·嵌入式硬件·电视盒子
OPEN-F21 小时前
Python进阶教程:Git版本控制与团队协作
git·python·elasticsearch
ellenwan202621 小时前
2026年量化入门:先连起概念、规则和简单实现
人工智能·python
2601_9669496521 小时前
Python 量化数据质量校验:如何确保股票历史日线数据不存在缺失交易日?
开发语言·人工智能·爬虫·python·量化策略·量化·quantdash
circuitsosk1 天前
Python 文件读写与上下文管理器:with 语句为什么是最佳选择
java·服务器·python·文件操作·上下文管理器·contextlib
whcyhhh1 天前
头歌实践教学平台:数据科学与大数据技术导论(七下)
大数据·数据库·python
Java后端的Ai之路1 天前
05、Python单例模式完全指南
开发语言·人工智能·python·单例模式·oracle