POI HSSF API를 사용하여 Excel Cell의 날짜 값 읽기
-
21-08-2019 - |
문제
Java의 Excel 조작에 Poi HSSF API를 사용하고 있습니다. Excel 셀 중 하나에 날짜 값 "8/1/2009"가 있으며 HSSF API를 사용 하여이 값을 읽으려고하는 동안 셀 유형을 숫자로 감지하고 날짜의 '이중'값을 반환합니다. 아래 샘플 코드를 참조하십시오.
cell = row.getCell(); // date in the cell '8/1/2009'
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
cellValue = cell.getRichStringCellValue().getString();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
cellValue = new Double(cell.getNumericCellValue()).toString();
break;
default:
}
cell.getCellType ()를 반환하면 Numeric_type를 반환하면이 코드는 날짜를 두 배로 변환합니다! :(
HSSF POI에서 날짜를 읽을 수있는 방법이 있습니까!?
해결책
당신은 다음을 볼 수 있습니다.
HSSFDateUtil.isCellDateFormatted()
hssfdateutil에 대한 자세한 내용은 POI 끔찍한 스프레드 시트 형식 API를 참조하십시오.
http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/hssfdateutil.html
또한 Excel을 반환하기위한 몇 가지 도우미 방법을 제공합니다 getExcelDate()
그리고 Java 날짜 getJavaDate()
. 그래도 다른 날짜 형식을 다소 조심해야합니다 ...
다른 팁
Excel 파일에서와 같은 형식으로 날짜를 참조하려면 CellDateFormatter를 사용해야합니다. 샘플 코드 :
CellValue cValue = formulaEv.evaluate(cell);
double dv = cValue.getNumberValue();
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = HSSFDateUtil.getJavaDate(dv);
String dateFmt = cell.getCellStyle().getDataFormatString();
/* strValue = new SimpleDateFormat(dateFmt).format(date); - won't work as
Java fmt differs from Excel fmt. If Excel date format is mm/dd/yyyy, Java
will always be 00 for date since "m" is minutes of the hour.*/
strValue = new CellDateFormatter(dateFmt).format(date);
// takes care of idiosyncrasies of Excel
}
Excel은 날짜와 시간을 숫자로 취급합니다 ... Jon은 그것을 더 잘 말했습니다. 그래서 나는 그를 여기에 반향하지 않을 것입니다 ...
그러나 질문에 넣은 것에 대한 샘플 코드는 다음과 같습니다. http://poi.apache.org/spreadsheet/quick-guide.html#cellcontents
POI 3.5를 사용하는 경우 다음을 사용할 수 있습니다.
cell.getDateCellValue () 메소드입니다. 이것은 Excel 2007에서도 작동합니다.
POI 3.15 Beta3 이후 일부 기능이 있습니다 deprecated
. 데이터 형식을 확인하고 Java로 검색 할 수 있습니다 Date
.
SimpleDateFormat format = new SimpleDateFormat("");
String cellValue;
if(cell != null && cell.getCellTypeEnum() != CellType.STRING &&
cell.getCellTypeEnum() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell)){
cellValue = format.format(cell.getDateCellValue());
}