민서네집

[Apache POI] 날짜 서식의 셀 데이터 읽기 본문

Java

[Apache POI] 날짜 서식의 셀 데이터 읽기

브라이언7 2015. 5. 7. 18:47

날짜 서식의 셀을 읽을 때 cell.getType() 값이 Cell.CELL_TYPE_NUMERIC 이 되서 당황했는데,

DateUtil.isCellDateFormatted(cell) 의 값이 true 이면

String.valueOf(cell.getDateCellValue()); 로 날짜 문자열을 얻으면 된다.


사용 Library: 


<dependency>

<groupId>org.apache.poi</groupId>

<artifactId>poi</artifactId>

<version>3.11</version>

</dependency>


참조: 

http://lovelyjk.tistory.com/28

http://stackoverflow.com/questions/10857209/issue-reading-in-a-cell-from-excel-with-apache-poi


private String getCellValue(FormulaEvaluator formulaEval, Cell cell) {


String cellString = "";


if( cell != null ) {

if (cell.getCellType() == Cell.CELL_TYPE_STRING)

cellString = cell.getStringCellValue();

else if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {

if( DateUtil.isCellDateFormatted(cell)) {

Date date = cell.getDateCellValue();

cellString = new SimpleDateFormat("yyyy-MM-dd").format(date);

}

else

cellString = String.valueOf(cell.getNumericCellValue());

}

else {

CellValue evaluate = formulaEval.evaluate(cell);

if( evaluate != null )

cellString = evaluate.formatAsString();

}

}


return cellString.trim();

}




Comments