1
1

More than 3 years have passed since last update.

関数を評価する前もしくは評価した後のセルの値が欲しい

Posted at

関数を評価した後の値が欲しい

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>
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1