計算式をセルに設定

広告

セルに計算式を設定する方法を確認します。

計算式を設定するにはCellインターフェースで用意されているsetCellFormulaメソッドを使います。

Sets formula for this cell.

Note, this method only sets the formula string and does not calculate the formula value.
To set the precalculated value use setCellValue(double) or setCellValue(String)

Parameters:
  formula - the formula to set, e.g. "SUM(C4:E4)". If the argument is null then the 
    current formula is removed. 
Throws:
  FormulaParseException - if the formula has incorrect syntax or is otherwise invalid

引数には計算式を表す文字列を指定して下さい。なお計算式の先頭の"="は不要です。

実際の使い方は次のようになります。

Workbook wb = new HSSFWorkbook();
Sheet sheet = web.createSheet();
Row row = sheet.createSheet(0);
Cell cell = row.createCell(0);

cell.setCellFormula("MOD(10,3)");

この場合は、セルに計算式"=MOD(10,3)"を設定しています。

サンプルプログラム

実際に試してみましょう。

Sample9_1.java

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import java.io.*;

public class Sample9_1{
  public static void main(String[] args){
    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet();
    Row row1 = sheet.createRow(1);
    Row row2 = sheet.createRow(2);

    Cell cell1_1 = row1.createCell(1);
    Cell cell1_2 = row1.createCell(2);
    Cell cell1_3 = row1.createCell(3);
    Cell cell2_3 = row2.createCell(3);

    cell1_1.setCellValue(30);
    cell1_2.setCellValue(25);
    cell1_3.setCellFormula("B2+C2");
    cell2_3.setCellFormula("MOD(B2,C2)");

    FileOutputStream out = null;
    try{
      out = new FileOutputStream("sample9_1.xls");
      wb.write(out);
    }catch(IOException e){
      System.out.println(e.toString());
    }finally{
      try {
        out.close();
      }catch(IOException e){
        System.out.println(e.toString());
      }
    }
  }
}

二つのセルに数値の値を設定し、別の二つのセルに先ほどの二つのセルに設定された値を使った計算式を設定しました。では作成されたExcelファイルを開いてみます。

計算式をセルに設定

計算式を設定すると、自動で計算も行われるようです。では計算式を設定したセルの値を確認してみます。

計算式をセルに設定

計算式をセルに設定

引数に指定した計算式が値として設定されていることが確認できます。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。