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

}

}

}

相关推荐
m0_70665323几秒前
自然语言处理(NLP)入门:使用NLTK和Spacy
jvm·数据库·python
m0_736919105 分钟前
Python游戏中的碰撞检测实现
jvm·数据库·python
aiguangyuan5 分钟前
使用PyTorch和Hugging Face Transformers构建GPT教学演示:从基础原理到实践应用
人工智能·python·nlp
颢珂智库Haokir Insights10 分钟前
可以将媒体项目自动转换成iPod支持的标准应用推荐
python·媒体
MarkHD10 分钟前
Python RPA入门实战:深入解析RPA核心概念与Python的优势(第5-6天)
开发语言·python·rpa
flysh0511 分钟前
Python 提取本机连接过WiFi名称和密码
python·wifi·password
曲幽12 分钟前
FastAPI部署实战:聊聊CORS跨域那些坑
python·fastapi·web·cors·corsmiddleware·origins
困死,根本不会15 分钟前
OpenCV摄像头实时处理:基于模板匹配的摄像头实时数字识别
python·opencv·计算机视觉
rainbow688916 分钟前
Java17新特性深度解析
java·开发语言·python
肆意飞扬19 分钟前
Python篇:使用conda、pip的一些命令记录
python·conda·pip