[java] Java Apache POI를 사용하여 Excel 파일의 수식 계산하기

Excel 파일에서 수식을 포함하는 셀을 읽고 계산 결과를 가져오려면 Java에서 Apache POI 라이브러리를 사용할 수 있습니다. Apache POI는 Java로 Excel 파일을 읽고 쓰는 데 사용되는 라이브러리입니다.

Apache POI 라이브러리 추가

먼저, Apache POI 라이브러리를 프로젝트에 추가해야 합니다. Maven을 사용하는 경우 pom.xml 파일에 다음 종속성을 추가합니다.

<dependencies>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>4.1.2</version>
    </dependency>
</dependencies>

Gradle을 사용하는 경우 build.gradle 파일에 다음 종속성을 추가합니다.

dependencies {
    implementation 'org.apache.poi:poi:4.1.2'
}

Excel 파일에서 수식 읽기

다음은 Excel 파일에서 수식을 읽는 예제 코드입니다.

import org.apache.poi.ss.usermodel.*;

import java.io.FileInputStream;
import java.io.InputStream;

public class ExcelFormulaReader {
    public static void main(String[] args) {
        try {
            InputStream inputStream = new FileInputStream("example.xlsx");
            Workbook workbook = WorkbookFactory.create(inputStream);

            Sheet sheet = workbook.getSheetAt(0);
            Row row = sheet.getRow(0);
            Cell cell = row.getCell(0);

            if (cell.getCellType() == CellType.FORMULA) {
                FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
                CellValue cellValue = evaluator.evaluate(cell);

                if (cellValue.getCellType() == CellType.NUMERIC) {
                    double result = cellValue.getNumberValue();
                    System.out.println("계산 결과: " + result);
                }
            }

            workbook.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

위 코드는 example.xlsx 파일의 첫 번째 시트의 첫 번째 셀에서 수식을 읽고 계산 결과를 출력합니다.

수식 계산 결과 가져오기

위 코드에서 CellValue 객체를 사용하여 수식의 계산 결과를 가져옵니다. CellValue 객체의 getCellType() 메소드를 사용하여 수식의 결과 타입을 확인한 다음, getNumberValue() 메소드를 사용하여 수식의 계산 결과를 얻을 수 있습니다.

결과 확인하기

위 코드를 실행하면 example.xlsx 파일의 첫 번째 시트의 첫 번째 셀에 있는 수식을 계산한 결과가 출력됩니다.

Apache POI를 사용하여 Excel 파일의 수식을 읽고 계산하는 방법에 대해 알아보았습니다. 이를 활용하여 Excel 파일에서 수식을 처리하고 원하는 결과를 얻을 수 있습니다.

참고 자료