作成済みのセルを取得

広告

既に作成済みのワークブックを開いた時に、値が設定されているセルは取得することができます。(値が設定されていないセルは実際には存在していないものとして扱われるため取得することはできません)。

セルを取得するにはRowインターフェースで用意されているgetCellメソッドを使います。

Get the cell representing a given column (logical cell) 0-based. If you ask for a cell 
that is not defined....you get a null. 

Returns:
  cellnum - 0 based column number 
Returns:
  Cell representing that column or null if undefined.

引数には列番号を指定して下さい。行の中に指定した列番号のセルが存在している場合には、そのセルを表すCellインターフェースを実装したクラスのオブジェクトを取得できます。存在しないセルを取得しようとするとnullが返されます。

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

InputStream in = new FileInputStream("filename.xls");
Workbook wb = WorkbookFactory.create(in);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(0);

Cell cell = row.getCell(2);

この場合、列番号が2のセルが存在していれば、そのセルを表すオブジェクトを取得します。もし行が存在していなければnullを取得します。

サンプルプログラム

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

Sample2_1.java

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import java.io.*;

public class Sample2_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);
    Row row1 = sheet.getRow(1);
    Row row2 = sheet.createRow(2);

    for (int i = 0 ; i < 6 ; i++){
      Cell cell = row1.getCell(i);
      if (cell != null){
        row2.createCell(i).setCellValue("Check!");
      }
    }

    FileOutputStream out = null;
    try{
      out = new FileOutputStream("sample2_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());
      }
    }
  }
}

事前に下記のようなシートが含まれるワークブックを作成しました。

作成済みのセルを取得

プログラムを実行すると1行目の行に対して列番号0から5までのセルを順に取得します。セルを取得できた場合には2行目の同じ列番号の位置にセルを作成し値を設定しています。それでは作成されたファイルをExcelで開いてみます。

作成済みの行を取得

列番号1と3のセルには値が設定されているためセルを取得することができました。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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