1. 程式人生 > >在java中匯入excel表格讀取Excel資料的日期格式

在java中匯入excel表格讀取Excel資料的日期格式

在ExcelReader類中.getStringCellValue()方法裡:

public static String getStringCellValue(Cell cell) {
if(cell == null){
return "";
}
String strCell = "";
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
strCell = cell.getStringCellValue();
break;
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();
strCell = sdf.format(date);
} else if (cell.getCellStyle().getDataFormat() == 58||cell.getCellStyle().getDataFormat() == 14||cell.getCellStyle().getDataFormat() == 57||cell.getCellStyle().getDataFormat() == 31) {
// 處理自定義日期格式: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);
strCell = 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("#");
}
strCell = format.format(value);
}
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
strCell = String.valueOf(cell.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_FORMULA://新加的公式型別
strCell =cell.getCellFormula().toString();
break;
case HSSFCell.CELL_TYPE_BLANK:
strCell = "";
break;
default:
strCell = "";
break;
}
if (strCell.equals("") || strCell == null) {
return "";
}
if (cell == null) {
return "";
}
return strCell;
}

    所有日期格式都可以通過getDataFormat()值ID值來判斷

yyyy-MM-dd-----    14

yyyy年m月d日---    31

yyyy年m月-------    57

m月d日  ----------    58

HH:mm-----------    20

h時mm分  -------    32