2016-07-04 3 views
1

내 Excel 시트에는 많은 셀에 수식이 들어 있으며 Apache POI로 Excel을 읽을 때이 수식을 다시 계산할 필요가 없습니다.POI-XSSF : 수식 셀 캐시 된 값에서 형식화 된 값을 읽습니다.

방법 내가 그렇게 :

if(cell.getCellType() == XSSFCell.CELL_TYPE_FORMULA) { 

    //System.out.println("Formula is " + cell.getCellFormula()); 
    switch(cell.getCachedFormulaResultType()) { 
     case XSSFCell.CELL_TYPE_NUMERIC: 

      System.out.print(cell.getNumericCellValue() +" "); 

      break; 
     case XSSFCell.CELL_TYPE_STRING: 
      System.out.print(cell.getRichStringCellValue()+" "); 
      break; 
    } 
} 

이 셀의 원시 값을 얻는 날 수 있습니다. 예를 들어 셀의 값이 19.5 %이면 0.195456이됩니다. 형식화 된 값을 가져오고 싶습니다. 포맷 된 값을 얻을 수

한 가지 방법은 다음과 같습니다

DataFormatter formatter = new DataFormatter(); 

System.out.print(formatter.formatCellValue(cell)); 

이 일반 세포에 잘 작동하지만, 수식 셀이 실제로 즉, 수식 문자열을 가져옵니다 그것을 표시, 그것은을하지 않습니다 캐쉬 된 값을 가져 와서 형식을 지정하지만 공식 문자열을 반환합니다.

CELL_TYPE_FORMULA에서 검색 한 후 값을 포맷 할 수있는 방법이 있나요

답변

3

당신이 즉, formatCellValue에 대한 호출에 FormulaEvaluator

DataFormatter formatter = new DataFormatter(); 
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); 
System.out.print(formatter.formatCellValue(cell, evaluator)); 
+1

실제로 수식은 제 3 자 플러그인에서 가져온 것이므로 사용하지 않으려 고합니다. 캐시 된 값만 올바르게 형식화해야합니다. – gaurav5430

2

을 통과한다면 그것은 직접 서식을 가능 작동합니다 평가자를 사용하지 않고 셀의 값을 캐시합니다. 제 3 자 플러그인 또는 셀 수식에서 사용할 수없는 외부 데이터로 인해 다시 계산할 수없는 값의 경우 유용합니다.

이 코드

는 그렇게 할 수 있습니다 :

final DataFormatter dataFormatter = new DataFormatter(); 

final CellStyle cellStyle = cell.getCellStyle(); 
final String formtatedValue = dataFormatter.formatRawCellContents(cell.getNumericCellValue(), cellStyle.getDataFormat(), cellStyle.getDataFormatString()); 
System.out.println(formattedValue); 

포맷터는 여전히 사용되지만 방법 formatRawCellContents은 수동으로 스타일 셀 캐시 값을 포맷이라고합니다.