package utils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class ExcelCellUtils {
private static Map<Class<?>, CellType[]> validateMap = new HashMap<>();
static {
validateMap.put(String[].class, new CellType[]{CellType.STRING});
validateMap.put(Double[].class, new CellType[]{CellType.NUMERIC});
validateMap.put(String.class, new CellType[]{CellType.STRING});
validateMap.put(Double.class, new CellType[]{CellType.NUMERIC});
validateMap.put(Date.class, new CellType[]{CellType.NUMERIC, CellType.STRING});
validateMap.put(Integer.class, new CellType[]{CellType.NUMERIC});
validateMap.put(Float.class, new CellType[]{CellType.NUMERIC});
validateMap.put(Long.class, new CellType[]{CellType.NUMERIC});
validateMap.put(Boolean.class, new CellType[]{CellType.BOOLEAN});
}
/**
* 获取cell类型的文字描述
*
* @param cellType <pre>
* CellType.BLANK
* CellType.BOOLEAN
* CellType.ERROR
* CellType.FORMULA
* CellType.NUMERIC
* CellType.STRING
* </pre>
* @return
*/
private static String getCellTypeByInt(CellType cellType) {
if(cellType == CellType.BLANK) {
return "Null type";
} else if(cellType == CellType.BOOLEAN) {
return "Boolean type";
} else if(cellType == CellType.ERROR) {
return "Error type";
} else if(cellType == CellType.FORMULA) {
return "Formula type";
} else if(cellType == CellType.NUMERIC) {
return "Numeric type";
} else if(cellType == CellType.STRING) {
return "String type";
} else {
return "Unknown type";
}
}
/**
* 获取单元格值
*
* @param cell
* @return
*/
public static Object getCellValue(Cell cell) {
if (cell == null
|| (cell.getCellTypeEnum() == CellType.STRING && StringUtils.isBlank(cell
.getStringCellValue()))) {
return null;
}
CellType cellType = cell.getCellTypeEnum();
if(cellType == CellType.BLANK) {
return null;
} else if(cellType == CellType.BOOLEAN) {
return cell.getBooleanCellValue();
} else if(cellType == CellType.ERROR) {
return cell.getErrorCellValue();
} else if(cellType == CellType.FORMULA) {
try {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
return cell.getDateCellValue();
} else {
return cell.getNumericCellValue();
}
} catch (IllegalStateException e) {
return cell.getRichStringCellValue();
}
}
else if(cellType == CellType.NUMERIC){
if (DateUtil.isCellDateFormatted(cell)) {
return cell.getDateCellValue();
} else {
return cell.getNumericCellValue();
}
}
else if(cellType == CellType.STRING) {
return cell.getStringCellValue();
} else {
return null;
}
}
}