- List item
//获取单元格各类型值,返回字符串类型
public static String getCellValueByCell(Cell cell) {
//判断是否为null或空串
if (cell==null || cell.toString().trim().equals("")) {
return “”;
}
String cellValue = “”;
int cellType=cell.getCellType();
switch (cellType) {
case Cell.CELL_TYPE_NUMERIC: // 数字
short format = cell.getCellStyle().getDataFormat();
if (DateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat sdf = null;
//System.out.println(“cell.getCellStyle().getDataFormat()=”+cell.getCellStyle().getDataFormat());
if (format == 20 || format == 32) {
sdf = new SimpleDateFormat(“HH:mm”);
} else if (format == 14 || format == 31 || format == 57 || format == 58) {
// 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
sdf = new SimpleDateFormat(“yyyy-MM-dd”);
double value = cell.getNumericCellValue();
Date date = org.apache.poi.ss.usermodel.DateUtil
.getJavaDate(value);
cellValue = sdf.format(date);
}else {// 日期
sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
}
try {
cellValue = sdf.format(cell.getDateCellValue());// 日期
} catch (Exception e) {
try {
throw new Exception(“exception on get date data !”.concat(e.toString()));
} catch (Exception e1) {
e1.printStackTrace();
}
}finally{
sdf = null;
}
} else {
BigDecimal bd = new BigDecimal(cell.getNumericCellValue());
cellValue = bd.toPlainString();// 数值 这种用BigDecimal包装再获取plainString,可以防止获取到科学计数值
}
break;
case Cell.CELL_TYPE_STRING: // 字符串
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN: // Boolean
cellValue = cell.getBooleanCellValue()+"";;
break;
case Cell.CELL_TYPE_FORMULA: // 公式
cellValue = cell.getCellFormula();
break;
case Cell.CELL_TYPE_BLANK: // 空值
cellValue = “”;
break;
case Cell.CELL_TYPE_ERROR: // 故障
cellValue = “ERROR VALUE”;
break;
default:
cellValue = “UNKNOW VALUE”;
break;
}
return cellValue;
}
导入EXCEL处理 日期格式
最新推荐文章于 2022-05-12 15:01:03 发布