- Home ›
- Apache POIでExcelを操作 ›
- 行 ›
- HERE
行からセルを削除
広告
行に追加されているセルを削除する方法を確認します。
行からセルを削除するにはRowインターフェースで用意されているremoveCellメソッドを使います。
removeCell void removeCell(Cell cell)
Remove the Cell from this row. Parameters: cell - the cell to remove
引数に削除したいセルを表すCellインターフェースを実装したクラスのオブジェクトを指定します。
実際の使い方は次のようになります。
InputStream in = new FileInputStream("filename.xls");
Workbook wb = WorkbookFactory.create(in);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(1);
Cell cell = row.getCell(1);
row.removeCell(cell);
この場合は1行目の行から列番号1のセルを削除しています。
サンプルプログラム
実際に試してみましょう。
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import java.io.*;
public class Sample5_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 row = sheet.getRow(1);
Cell cell = row.getCell(1);
row.removeCell(cell);
FileOutputStream out = null;
try{
out = new FileOutputStream("sample5_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ファイルを用意しています。
プログラムを実行すると、1行目の中の1列目のセルを取得した後で行から削除しています。それでは作成されたファイルをExcelで開いてみます。
セルが削除されていることを確認できます。
( Written by Tatsuo Ikura )
JavaDrive