関数を評価した後の値が欲しい
Apache POIでセルの値を取得する際、「セルに関数が含まれている場合は関数を評価した後の値が欲しい」とします。書き方はいろいろあるのですが、おおよそ以下のようにすればよいです。
// WorkBookオブジェクトからFormulaEvaluatorを生成する。
FormulaEvaluator formulaEvaluator = book.getCreationHelper().createFormulaEvaluator();
// CellのCellTypeを取得する。Cellが関数を含む場合は関数の評価後のCellTypeを取得する。
CellType cellType = (cell.getCellType() == CellType.FORMULA) ? formulaEvaluator.evaluateFormulaCell(cell) : cell.getCellType();
// CellTypeにあわせて値を取得する。ここではサンプルとして文字列型を取得している。
if (cellType == CellType.STRING) {
String stringCellValue = cell.getStringCellValue();
doSomething(stringCellValue);
}
関数を評価する前の値が欲しい / 関数そのものが欲しい
上とは違って、セルに含まれている関数そのものが欲しい場合は、Cell::getCellFormula
を利用します。
if (cell.getCellType() == CellType.FORMULA) {
String cellFormula = cell.getCellFormula();
doSomething(cellFormula);
}
動作確認環境 (pom.xmlより抜粋)
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.0.0</version>
</dependency>