import cn.com.wind.fixedincome.abs.common.constant.ErrorCode;
import cn.com.wind.fixedincome.abs.common.exception.BusinessException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ExcelUtil {
private ExcelUtil() {
}
public static String excelToJsonStr(String excelPath) {
try {
ClassLoader classLoader = ExcelUtil.class.getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(excelPath);
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int rowCount = sheet.getPhysicalNumberOfRows();
List<Map<String, Object>> data = new ArrayList<>();
Map<Integer, String> headerMap = new HashMap<>();
Row headerRow = sheet.getRow(0);
int headerCount = headerRow.getPhysicalNumberOfCells();
for (int i = 0; i < headerCount; i++) {
Cell headerCell = headerRow.getCell(i);
if (headerCell != null) {
headerMap.put(i, headerCell.getStringCellValue());
}
}
for (int i = 1; i < rowCount; i++) {
Row row = sheet.getRow(i);
Map<String, Object> rowData = new HashMap<>();
int cellCount = row.getPhysicalNumberOfCells();
for (int j = 0; j < cellCount; j++) {
Cell cell = row.getCell(j);
if (cell != null) {
switch (cell.getCellType()) {
case STRING:
rowData.put(headerMap.get(j), cell.getStringCellValue());
break;
case NUMERIC:
rowData.put(headerMap.get(j), cell.getNumericCellValue() == 0 ? "0" : cell.getNumericCellValue());
break;
case BOOLEAN:
rowData.put(headerMap.get(j), cell.getBooleanCellValue());
break;
case FORMULA:
rowData.put(headerMap.get(j), cell.getCellFormula());
break;
}
}
}
data.add(rowData);
}
workbook.close();
return ObjectMapperUtil.toJSONString(data);
} catch (IOException exception) {
throw new BusinessException(ErrorCode.B_0001, "Excel转换失败");
}
}
/**
* 读取resources目录下文件
*
* @param fileName
* @return
* @throws Exception
*/
public static String readResourceFile(String fileName) throws Exception {
ClassLoader classLoader = YunPanTreeModelUtil.class.getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(fileName);
if (inputStream == null) {
throw new BusinessException(ErrorCode.B_0001, "File not found: {}" + fileName);
}
StringBuilder content = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
}
return content.toString();
}
}
Excel数据转json工具类
于 2023-12-29 13:19:43 首次发布