作成済みの行を取得

広告

既に作成済みのワークブックを開く場合、ワークブックの中のシートにはすでにどこかのセルに値が設定されているかもしれません。その場合、そのセルが含まれる行を取得することができます。(逆に値が設定されているセルが一つもない行は、存在していないので取り出すことができません)。

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

Returns the logical row (not physical) 0-based. If you ask for a row that is not 
defined you get a null. This is to say row 4 represents the fifth row on a sheet. 

Parameters:
  rownum - row to get (0-based)
Returns:
  Row representing the rownumber or null if its not defined on the sheet

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

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

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

Row row = sheet.getRow(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);

    for (int i = 0 ; i < 6 ; i++){
      Row row = sheet.getRow(i);
      if (row != null){
        Cell cell = row.createCell(0);
        cell.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());
      }
    }
  }
}

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

作成済みの行を取得

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

作成済みの行を取得

行番号1と4の行には値が設定されたセルが含まれていましたので行を取得することができました。その為、行番号1と4の0列目のセルに値が設定されています。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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