Excel存储日期、时间均以数值类型进行存储,读取时先使用POI判断是否是数值类型,再进行进一步判断是否为日期,最后转化
1.纯数值格式:getNumericCellValue() 直接获取数据
2.日期格式:处理yyyy-MM-dd, d/m/yyyy h:mm, HH:mm 等不含文字的日期格式
1).判断是否是日期格式:HSSFDateUtil.isCellDateFormatted(cell)
2).判断是日期或者时间
cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat(“h:mm”)
OR: cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat(“yyyy-MM-dd”)
3.自定义日期格式:处理yyyy年m月d日,h时mm分,yyyy年m月等含文字的日期格式
判断cell.getCellStyle().getDataFormat()值,解析数值格式
yyyy年m月d日----->31
m月d日---->58
h时mm分—>32
例:
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC: // 数字类型
if (HSSFDateUtil.isCellDateFormatted(cell)) { // 处理日期格式、时间格式
SimpleDateFormat sdf = null ;
if (cell.getCellStyle().getDataFormat() == HSSFDataFormat
.getBuiltinFormat( "h:mm" )) {
sdf = new SimpleDateFormat( "HH:mm" );
} else { // 日期
sdf = new SimpleDateFormat( "yyyy-MM-dd" );
}
Date date = cell.getDateCellValue();
result = sdf.format(date);
} else if (cell.getCellStyle().getDataFormat() == 58 ) {
// 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
double value = cell.getNumericCellValue();
Date date = org.apache.poi.ss.usermodel.DateUtil
.getJavaDate(value);
result = sdf.format(date);
} else {
double value = cell.getNumericCellValue();
CellStyle style = cell.getCellStyle();
DecimalFormat format = new DecimalFormat();
String temp = style.getDataFormatString();
// 单元格设置成常规
if (temp.equals( "General" )) {
format.applyPattern( "#" );
}
result = format.format(value);
}
break ;
*通用处理方案:
所有日期格式都可以通过getDataFormat()值来判断
yyyy-MM-dd----- 14
yyyy年m月d日— 31
yyyy年m月------- 57
m月d日 ---------- 58
HH:mm----------- 20
h时mm分 ------- 32
例:
String cellValue = “”;
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_STRING:// 字符串类型
cellValue = cell.getStringCellValue();
if (cellValue.trim().equals("") || cellValue.trim().length() <= 0)
cellValue = "";
break;
case XSSFCell.CELL_TYPE_NUMERIC: // 数值类型
short format = cell.getCellStyle().getDataFormat();
SimpleDateFormat sdf = null;
if (format == 14 || format == 31 || format == 57 || format == 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 {
// 返回数值类型的值
Long longVal = Math.round(cell.getNumericCellValue());
Double doubleVal = cell.getNumericCellValue();
if (Double.parseDouble(longVal + ".0") == doubleVal) { // 判断是否含有小数位.0
cellValue = longVal.toString();
} else {
cellValue = doubleVal.toString();
}
}
break;
————————————————
原文链接:https://blog.csdn.net/weixin_38084097/article/details/77242508