セルに設定された値を取得

広告

セルに設定された様々な種類の値を取得する方法を確認します。値を取得するためのメソッドはCellインターフェースで用意されていますが、設定されている値の種類に応じて別々のメソッドが用意されています。

戻り値メソッド
StringgetCellFormula
doublegetNumericCellValue
DategetDateCellValue
RichTextStringgetRichStringCellValue
StringgetStringCellValue
booleangetBooleanCellValue
bytegetErrorCellValue

文字列の値が設定されているセルから値を取得するにはgetStringCellValueメソッドを使い、数値が設定されているセルから値を取得するにはgetNumericCellValueメソッドを使います。他のタイプの値が設定されているセルに対してメソッドを実行することもできますが、変換できない値だった場合などは例外が発生します。

ここではまず数値と文字列、そして日付の値を取得するためのメソッドについて確認します。

数値の値を取得するにはCellインターフェースで用意されているgetNumericCellValueメソッドを使います。

Get the value of the cell as a number.

For strings we throw an exception. For blank cells we return a 0. For formulas or error 
cells we return the precalculated value; 

Returns:
  the value of the cell as a number 
Throws:
  java.lang.IllegalStateException - if the cell type returned by getCellType() 
    is CELL_TYPE_STRING
  java.lang.NumberFormatException - if the cell value isn't a parsable double.

セルに設定されている値をdouble型の値として返します。このメソッドの場合、対象のセルのセルタイプがCELL_TYPE_STRINGだったり、設定されている値をdouble型の値に変換できなかった場合には例外が発生します。

--*--*--

文字列の値を取得するにはCellインターフェースで用意されているgetStringCellValueメソッドを使います。

Get the value of the cell as a string

For numeric cells we throw an exception. For blank cells we return an empty string. For 
formulaCells that are not string Formulas, we return empty String. 

Returns:
  the value of the cell as a string

セルに設定されている値を文字列の値として返します。このメソッドの場合、計算式が設定されているセルから値を取得すると、空の文字列が返される点に注意して下さい。

--*--*--

日付の値を取得するにはCellインターフェースで用意されているgetDateCellValueメソッドを使います。

Get the value of the cell as a date.

For strings we throw an exception. For blank cells we return a null. 

Returns:
  the value of the cell as a date 
Throws:
  java.lang.IllegalStateException - if the cell type returned by getCellType() 
    is CELL_TYPE_STRING 
  java.lang.NumberFormatException - if the cell value isn't a parsable double.

セルに設定されている値をjava.util.Dateクラスのオブジェクトとして返します。このメソッドの場合、対象のセルのセルタイプがCELL_TYPE_STRINGだったり、設定されている値をdouble型の値に変換できなかった場合には例外が発生します。

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

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

double val = cell.getNumericCellValue();

この場合は、セルに設定されている値をdouble型の値として取得します。

サンプルプログラム

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

Sample7_1.java

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

public class Sample7_1{
  public static void main(String[] args){
    FileInputStream in = null;
    Workbook wb = null;

    try{
      in = new FileInputStream("sample.xls");
      wb = WorkbookFactory.create(in);
    }catch(IOException e){
      System.out.println(e.toString());
    }catch(InvalidFormatException e){
      System.out.println(e.toString());
    }finally{
      try{
        in.close();
      }catch (IOException e){
        System.out.println(e.toString());
      }
    }

    Sheet sheet = wb.getSheetAt(0);

    for (int i = 1 ; i < 8 ; i++){
      Row row = sheet.getRow(i);
      if (row == null){
        row = sheet.createRow(i);
      }

      Cell cell1 = row.getCell(1);
      if (cell1 == null){
        cell1 = row.createCell(1);
      }

      switch(cell1.getCellType()) {
      case Cell.CELL_TYPE_STRING:
        System.out.println("String:" + cell1.getStringCellValue());
        break;
      case Cell.CELL_TYPE_NUMERIC:
        if(DateUtil.isCellDateFormatted(cell1)) {
          System.out.println("Date:" + cell1.getDateCellValue());
        } else {
          System.out.println("Numeric:" + cell1.getNumericCellValue());
        }
        break;
      case Cell.CELL_TYPE_BOOLEAN:
        System.out.println("Boolean:" + cell1.getBooleanCellValue());
        break;
      case Cell.CELL_TYPE_FORMULA:
        System.out.println("Formula:" + cell1.getCellFormula());
        break;
      case Cell.CELL_TYPE_ERROR :
        System.out.println("Error:" + cell1.getErrorCellValue());
        break;
      case Cell.CELL_TYPE_BLANK  :
        System.out.println("Blank:");
        break;
      }
    }
  }
}

事前に次のようなExcelファイルを用意してあります。

セルに設定された値を取得

プログラムを実行すると、セルに設定されたセルタイプに応じ、対応するメソッドを使ってセルに設定された値を取得し標準出力へ出力します。実際には下記のように出力されました。

セルに設定された値を取得

セルの値を取得できることが確認できました。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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