POI Excel 单元格内容类型判断并取值
个人用到的
String birthdayVal = null;
switch (cell_2.getCellTypeEnum()) {
case STRING:
birthdayVal = cell_2.getRichStringCellValue().getString();
break;
case NUMERIC:
if(“General”.equals(cell_2.getCellStyle().getDataFormatString())){
birthdayVal =DateToStr(HSSFDateUtil.getJavaDate(cell_2.getNumericCellValue()));
}else if(“m/d/yy”.equals(cell_2.getCellStyle().getDataFormatString())){
birthdayVal = DateToStr(cell_2.getDateCellValue());
}else{
birthdayVal = DateToStr(HSSFDateUtil.getJavaDate(cell_2.getNumericCellValue()));
}
break;
default:
x = i+1;
throw new AWSForbiddenException(“导入文件的第[“+x+”]行的[出生年月]的格式有问题,请检查!”,null);
}
/**
* 日期转换成字符串
*/
public static String DateToStr(Date date) {
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(“yyyy-MM-dd”);
String str = format.format(date);
return str;
}
————————————————————————————————————————————————————————–
poi3.5之前的版本
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC: // 数字
//如果为时间格式的内容
if (HSSFDateUtil.isCellDateFormatted(cell)) {
//注:format格式 yyyy-MM-dd hh:mm:ss 中小时为12小时制,若要24小时制,则把小h变为H即可,yyyy-MM-dd HH:mm:ss
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);
value=sdf.format(HSSFDateUtil.getJavaDate(cell.
getNumericCellValue())).toString();
break;
} else {
value = new DecimalFormat(“0”).format(cell.getNumericCellValue());
}
break;
case HSSFCell.CELL_TYPE_STRING: // 字符串
value = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
value = cell.getBooleanCellValue() + “”;
break;
case HSSFCell.CELL_TYPE_FORMULA: // 公式
value = cell.getCellFormula() + “”;
break;
case HSSFCell.CELL_TYPE_BLANK: // 空值
value = “”;
break;
case HSSFCell.CELL_TYPE_ERROR: // 故障
value = “非法字符”;
break;
default:
value = “未知类型”;
break;
}
poi3.5以后版本
switch (cell.getCellTypeEnum()) {
case STRING:
value = cell.getRichStringCellValue().getString();
break;
case NUMERIC:
if(“General”.equals(cell.getCellStyle().getDataFormatString())){
value = df.format(cell.getNumericCellValue());
}else if(“m/d/yy”.equals(cell.getCellStyle().getDataFormatString())){
value = sdf.format(cell.getDateCellValue());
}else{
value = df2.format(cell.getNumericCellValue());
}
break;
case BOOLEAN:
value = cell.getBooleanCellValue();
break;
case BLANK:
value = “”;
break;
default:
value = cell.toString();
break;
}