Don't say much, just go to the code.
java
package org.bood.common.utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Excel转Json
*
* @author bood
* @since 2024/10/30
*/
public class ExcelToJsonConverter {
public static void main(String[] args) {
String excelFilePath = "/Users/bood/Downloads/*.xlsx";
try {
List<Map<String, Object>> jsonData = convertExcelToJson(excelFilePath);
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonData);
System.out.println(jsonString);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 将Excel文件转换为JSON格式的数据
* 此方法读取Excel文件的内容,并将其转换为一个包含多个键值对的列表
* 每个键值对代表Excel中的一个单元格,键是列标题,值是单元格的值
*
* @param filePath Excel文件的路径
* @return 包含多个键值对的列表,每个键值对代表Excel中的一个单元格
* @author bood
* @since 2024/12/02
*/
public static List<Map<String, Object>> convertExcelToJson(String filePath) throws IOException {
List<Map<String, Object>> jsonData = new ArrayList<>();
try (FileInputStream fis = new FileInputStream((filePath));
Workbook workbook = new XSSFWorkbook(fis)) {
// 获取第一个工作表
Sheet sheet = workbook.getSheetAt(0);
Row headerRow = sheet.getRow(0);
List<String> headers = new ArrayList<>();
// 获取列标题(KEY)
for (Cell cell : headerRow) {
headers.add(cell.toString());
}
// 读取数据行
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
if (row == null) continue;
Map<String, Object> jsonRow = new HashMap<>();
for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
Cell cell = row.getCell(j);
jsonRow.put(headers.get(j), getCellValue(cell));
}
jsonData.add(jsonRow);
}
}
return jsonData;
}
private static Object getCellValue(Cell cell) {
switch (cell.getCellTypeEnum()) {
case STRING:
return cell.getStringCellValue();
case BOOLEAN:
return cell.getBooleanCellValue();
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
return cell.getDateCellValue();
} else {
return Double.valueOf(cell.getNumericCellValue()).longValue();
}
case FORMULA:
return cell.getCellFormula();
case BLANK:
return null;
default:
return null;
}
}
}