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

}

}

}

相关推荐
天天被压力几秒前
【A股分钟级高频数据完全手册 #02】Python调用股票1分钟数据接口:Pro版最新分时取数与字段解析
java·人工智能·python
天天被压力19 分钟前
【A股分钟级高频数据完全手册 #01】Pro版接口体系总览与REST鉴权:42篇地图与从0接入
java·人工智能·python
xyouyuweizhu23 分钟前
Java InetAddress 详解:从 IP 地址表示到主机名解析
java·开发语言·python
belldeep9 小时前
python:genesis-world, Genesis-Embodied-AI
人工智能·python·ai·genesis
benchmark_cc10 小时前
A 股、港股、美股如何建立统一的标的主数据格式?
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
维克兜率天11 小时前
【维克】趋势型CTA:期货市场的“追涨杀跌“
人工智能·python
取名真是11 小时前
Python 算法知识点从基础到进阶
开发语言·python·算法
梦想不只是梦与想12 小时前
PyTorch、CPU、GPU、CUDA
人工智能·pytorch·python·深度学习·机器学习·cuda
数字融合12 小时前
透明化视频孪生危化安全管控解决方案
人工智能·python·安全
别问!问就是全会13 小时前
Jupyter Notebook 安装包下载|单元格分块运行,图表直接内嵌
ide·python·其他·jupyter