Apache Poi를 통해 엑셀을 다루는 중에 "미리 작성된 양식" 을 불러와서, 적절한 위치에 값을 넣어줬음에도 작성되어있는 수식함수가 업데이트가 안 되는 경우 가 있었습니다. 해당 상황에서 문제 해결 방법을 공유 합니다.     ...

[안드로이드] Apache Poi 엑셀 수식함수 동작안함 (formula not working)

Apache Poi를 통해 엑셀을 다루는 중에 "미리 작성된 양식"을 불러와서,

적절한 위치에 값을 넣어줬음에도

작성되어있는 수식함수가 업데이트가 안 되는 경우가 있었습니다.

해당 상황에서 문제 해결 방법을 공유 합니다.

 

 

 

 

 

 

 

1. 해결 방법(1) : 재정의

아래와 같이 특정 Cell의 수식함수를 재정의 해주는 방법이 있습니다.

fun setCellFormula(sheet: Sheet, rowIndex: Int, columnIndex: Int, formula: String) {
var row = sheet.getRow(rowIndex)
if (row == null) row = sheet.createRow(rowIndex)

var cell = row.getCell(columnIndex)
if (cell == null) cell = row.createCell(columnIndex)

cell.cellFormula = formula
}

 

물론 재정의를 통해 결과값이 잘 계산되서 나오는걸 확인은 했지만...

이미 수식 함수가 정의되어있는 양식에 다시 재정의하는건 효율적이지는 않은 것 같습니다.

 

 

 

 

 

 

 

2. 해결 방법(2) : FormulaEvaluator

엑셀의 수식 평가관련하여 FormulaEvaluator를 찾을 수 있었습니다.

FormulaEvaluator 정의되어 있는 여러 메서드가 있는데 

그 중 수식을 평가해주고 저장하는 evaluateFormulaCell 메서드를 활용할 수 있습니다.




[특정 Cell 수식 함수 업데이트]

fun evaluateFormulaCell(cell: Cell) {
val xssfFormulaEvaluator = XSSFFormulaEvaluator(xssfWorkbook)
if (cell.cellType == CellType.FORMULA) {
xssfFormulaEvaluator.evaluateFormulaCell(cell)
}
}



[특정 Sheet 수식 함수 업데이트]

fun evaluateFormulaSheet(sheet: Sheet) {
val xssfFormulaEvaluator = XSSFFormulaEvaluator(xssfWorkbook)
for (row in sheet) {
for (cell in row) {
if (cell.cellType == CellType.FORMULA) {
xssfFormulaEvaluator.evaluateFormulaCell(cell)
}
}
}
}

 

 

[모든 수식 함수 업데이트] : Excel 내용이 많으면 시간이 오래 걸릴 수 있습니다

fun evaluateFormulaAll() {
XSSFFormulaEvaluator.evaluateAllFormulaCells(xssfWorkbook)
}

 

 

그 외에도 FormulaEvaluator 관련 메서드를 참조하시려면 아래 링크를 확인해주세요.

Apache Poi : FormulaEvaluator

 

 

 

 

 

[Reference]

StackOverFlow

 

 

 

 

 

0 comments: