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

}

}

}

相关推荐
代码小书生17 小时前
time,一个时间操作的 Python 库!
开发语言·python·microsoft
IT策士17 小时前
Django 从 0 到 1 打造完整电商平台:收货地址管理
后端·python·django
麻雀飞吧17 小时前
TqWebHelper 本地监控:图表不刷新与端口冲突排查
前端·python
专注VB编程开发20年18 小时前
Python 的 C 扩展,本质上就是“去中心化的 COM”
java·服务器·开发语言·ide·python
TechWayfarer18 小时前
营销反作弊实战:用IP归属地查询平台识别虚假流量
网络·python·网络协议·tcp/ip·数据分析
天天爱吃肉821818 小时前
2026北京车展专题|电控产品及技术全景解读:集成化、高压化、碳化硅成主流
人工智能·python·功能测试·嵌入式硬件·汽车
biter down18 小时前
5:GUI自动化等待机制
运维·python·自动化
萌新小码农‍19 小时前
Python的input函数
java·前端·python
NiceCloud喜云19 小时前
AutoClaw 接入自定义 Anthropic 端点:让 Kanban 工作流跑在自己的模型路由上
java·开发语言·c++·人工智能·python·eclipse·batch