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;