处理复杂Excel表格数据读取问题
package com.jeesite.modules.ma.common.constant;
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.util.CellRangeAddress;
public class ExcelUtils {
public static Object getCellValue(Cell cell) {
switch (cell.getCellType()) {
case 0:
cell.setCellType(Cell.CELL_TYPE_STRING);
return cell.getStringCellValue();
case 1:
return cell.getStringCellValue();
case 2:
return cell.getCellFormula();
default:
return "";
}
}
public static CellRangeAddress getMergedRegion(Sheet sheet, int rownum, int colnum) {
int mergedCount = sheet.getNumMergedRegions();
for (int i = 0; i < mergedCount; i++) {
CellRangeAddress mergedRegion = sheet.getMergedRegion(i);
int firstRow = mergedRegion.getFirstRow();
int lastRow = mergedRegion.getLastRow();
int firstCol = mergedRegion.getFirstColumn();
int lastCol = mergedRegion.getLastColumn();
if ((rownum >= firstRow && rownum <= lastRow) && (colnum >= firstCol && colnum <= lastCol)) {
return mergedRegion;
}
}
return null;
}
public static String getMergedRegionValue(Sheet sheet, CellRangeAddress mergedRegion) {
int firstRow = mergedRegion.getFirstRow();
int lastRow = mergedRegion.getLastRow();
int firstCol = mergedRegion.getFirstColumn();
int lastCol = mergedRegion.getLastColumn();
StringBuilder sb = new StringBuilder();
for (int i = firstRow; i <= lastRow; i++) {
Row row = sheet.getRow(i);
if (row != null) {
for (int j = firstCol; j <= lastCol; j++) {
Cell cell = row.getCell(j);
if (cell != null) {
sb.append(getCellValue(cell)).append("\t");
} else {
sb.append("\t");
}
}
}
}
return sb.toString();
}
public static boolean isEmptyRow(Row row) {
if (row == null || row.getLastCellNum() <= 0) {
return true;
}
for (int i = 0; i < row.getLastCellNum(); i++) {
Cell cell = row.getCell(i);
if (cell != null && cell.getCellType() != 3) {
return false;
}
}
return true;
}
}