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

}

}

}

相关推荐
新子y6 分钟前
【小白笔记】最大交换 (Maximum Swap)问题
笔记·python
程序员爱钓鱼1 小时前
Python编程实战 · 基础入门篇 | Python的缩进与代码块
后端·python
pr_note2 小时前
python|if判断语法对比
python
apocelipes4 小时前
golang unique包和字符串内部化
java·python·性能优化·golang
Geoking.5 小时前
NumPy zeros() 函数详解
python·numpy
Full Stack Developme5 小时前
java.text 包详解
java·开发语言·python
丁浩6666 小时前
Python机器学习---2.算法:逻辑回归
python·算法·机器学习
B站_计算机毕业设计之家6 小时前
计算机毕业设计:Python农业数据可视化分析系统 气象数据 农业生产 粮食数据 播种数据 爬虫 Django框架 天气数据 降水量(源码+文档)✅
大数据·爬虫·python·机器学习·信息可视化·课程设计·农业
Q_Q5110082857 小时前
python+uniapp基于微信小程序的旅游信息系统
spring boot·python·微信小程序·django·flask·uni-app·node.js
鄃鳕7 小时前
python迭代器解包【python】
开发语言·python