金子邦彦研究室プログラミングJava のプログラム例Excel ファイルの入出力

Excel ファイルの入出力

Excel ファイルの新規作成.セルの値の読み込み.セルの値の更新.

関連する外部ページ】 http://www.stackasterisk.jp/tech/java/poi01_01.jsp で公開されていた記事を参考にしました.

ダウンロードと展開

  1. ディレクトリ c:\Program Files\java\poi25 を作る.
  2. Apache Jakarta Project の POI の Web ページ https://jakarta.apache.org/poi/index.html

    poi-bin-2.5.1-final-20040804.zip をダウンロードし,展開(解凍)する. 出来たファイルを,c:\Program Files\java\poi25 ディレクトリの下に置く.

  3. Windows環境変数 CLASSPATH に
    ;c:\Program Files\java\poi25
    
    追加する

サンプルプログラム

  1. Eclipse での作業.新規プロジェクトの作成

    「File (ファイル)」→「New (新規)」→「Project (プロジェクト)」

    プロジェクトの種類は Java プロジェクト.プロジェクト名は好きに付ける.

  2. POI を使えるように設定

    コンパイル前に,パッケージ・エキスプローラ内のプロジェクト名を右クリック.

    ウインドウが現れるので,「Properties」. 別のウインドウが現れるので,「Java Build Path」

    ウインドウが現れるので, C:\Program Files\java\poi25\poi-2.5.1-final-20040804.jar を指定する.

  3. (オプション) Java ソースの添付

    これで,Javadoc コメントのポップアップ表示やソースの閲覧ができるようになる

  4. 新しいパッケージと,クラス ExcelFileHandler とクラス Main の作成

    パッケージ・エクスプローラで, 「新規」→「クラス」

  5. クラス ExcelFileHandler と Main の定義(下記の通り)

ExcelHandler.java

package hoge.hoge.com;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import org.apache.poi.hssf.usermodel.*;

public class ExcelHandler {
  String fileName;
  File excelFile;
  FileInputStream inStream;
  HSSFWorkbook excelBook;
  int numOfSheets;
  String [] sheetsName;
  HSSFSheet [] sheets;

  /* コンストラクタでは,ファイル名をセット */
  public ExcelHandler( String f ) {
    fileName = f;
  }
  /*
   * 既存のエクセルファイルのオープン.ファイル名は,コンストラクタ呼び出しにおいてセットしておくこと
   */
  public void fileopen()
  {
    try {
      excelFile = new File(fileName);
      inStream = new FileInputStream(excelFile);
      excelBook = new HSSFWorkbook(inStream);
        numOfSheets = excelBook.getNumberOfSheets();
       
      sheetsName = new String[numOfSheets];
        for (int i = 0; i < numOfSheets; i++) {
          sheetsName[i] = excelBook.getSheetName(i);
        }
      sheets = new HSSFSheet[numOfSheets];
        for (int i = 0; i < numOfSheets; i++) {
          sheets[i] = excelBook.getSheetAt(i);
        }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void fileclose()
  {
    try {
      /* 書き込み結果のフラッシュ */
      FileOutputStream out = new FileOutputStream( excelFile );
      excelBook.write( out );
      out.close();
    } catch (IOException e) {
      e.printStackTrace();
    }    
     
    /* instream のクローズ */
    if (inStream != null) {
      try {
        excelBook = null;
        numOfSheets = 0;
        inStream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }    
  }
  /*
   * 新規エクセルファイルの作成.ファイル名は,コンストラクタ呼び出しにおいてセットしておくこと
   * シート数は1.シート名は,パラメータで設定.
   */
  public void createExcelWorkbook( int numOfSheets, String [] sheetName )
  {
    try {  
      /* エクセルワークブックの初期化 */
      HSSFWorkbook workBook = new HSSFWorkbook();
      /* ワークシートの作成 */
      for ( int i = 0; i < numOfSheets; i++ ) {
        HSSFSheet newSheet = workBook.createSheet();
              workBook.setSheetName(i, sheetName[i], HSSFWorkbook.ENCODING_UTF_16);
        /* 左上のセルオブジェクトを作っておく */
          HSSFRow newRow = newSheet.createRow(0);
          newRow.createCell((short)0);
      }
     
        /* 書き出し */
        FileOutputStream out = new FileOutputStream( new File( fileName ) );
        workBook.write( out );
        out.close();

        fileopen();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
    /* HSSFCell オブジェクトの取得.
     * すでに fileopen() を実行しておくこと.
     * 範囲外のときは,HSSFCell オブジェクトの生成を試みる..
     */
  public HSSFCell getcell(short sheetNum, short x, int y)
  {
    if ( sheetNum >= numOfSheets )
      return null;
    if ( y > sheets[sheetNum].getLastRowNum() ) {
      for( int i = sheets[sheetNum].getLastRowNum() + 1; i <= y; i++ ) {
        System.out.println("i="+i);
          sheets[sheetNum].createRow(i);
      }
    }
    HSSFRow row = sheets[sheetNum].getRow(y);
    if ( row == null )
      return null;
    if ( x >= row.getLastCellNum() ) {
      for( int i = row.getLastCellNum() + 1; i <= x; i++ ) {
          row.createCell((short)i);
      }      
    }
    HSSFCell cell = row.getCell(x);
      if ( cell == null ) {
        row.createCell(x);
        if ( cell == null )
          return null;
      }
    return cell;
  }
  /*
   * HSSFCell の値を System.out.print で表示
   */
  public void dispcell( HSSFCell cell )
  {
    if ( cell == null )
      return;
    int type = cell.getCellType();
    switch (type) {
    case HSSFCell.CELL_TYPE_BLANK :
        System.out.print("");   break;
    case HSSFCell.CELL_TYPE_BOOLEAN :
        System.out.print(cell.getBooleanCellValue());  break;
    case HSSFCell.CELL_TYPE_ERROR :
        System.out.print("ERROR");  break;
    case HSSFCell.CELL_TYPE_NUMERIC :
        System.out.print((int) cell.getNumericCellValue());  break;
    case HSSFCell.CELL_TYPE_STRING :
        System.out.print(cell.getStringCellValue());   break;
    case HSSFCell.CELL_TYPE_FORMULA :
        System.out.print(cell.getCellFormula());  break;
    default :
        System.out.print("");  break;
    }
  }
  /*
   * dispcell() を繰り返し実行して,全体を表示.
   */
    public void dispinfo() {
      try {
        for (short i = 0; i < numOfSheets; i++) {
          System.out.println("【" + sheetsName[i] + "】");
    
          for (int j = 0; j <= sheets[i].getLastRowNum(); j++) {
            HSSFRow row = sheets[i].getRow(j);
            if (row == null)
              continue;
            for (short k = 0; k < row.getLastCellNum(); k++) {
              HSSFCell cell = getcell(i,k,j);
              dispcell(cell);
              System.out.print(" | ");
            }
            System.out.println("\n------------------" +
                    "----------------------------------------");
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
   
    void setBooleanCellValue( short sheetNum, short x, int y, boolean val ) {
      HSSFCell cell = getcell( sheetNum, x, y );
      if ( cell == null ) {
        return;
      }
      cell.setCellType( HSSFCell.CELL_TYPE_BOOLEAN );
      cell.setCellValue( val );
      return;
    }
    void setNumericCellValue( short sheetNum, short x, int y, double val ) {
      HSSFCell cell = getcell( sheetNum, x, y );
      if ( cell == null ) {
        return;
      }
      cell.setCellType( HSSFCell.CELL_TYPE_NUMERIC );
      cell.setCellValue( val );
      return;
    }
    void setStringCellValue( short sheetNum, short x, int y, String val ) {
      HSSFCell cell = getcell( sheetNum, x, y );
      if ( cell == null ) {
        return;
      }
      cell.setCellType( HSSFCell.CELL_TYPE_STRING );
      cell.setEncoding(HSSFCell.ENCODING_UTF_16);
      cell.setCellValue( val );
      return;
    }
    void setCalendarCellValue( short sheetNum, short x, int y, Calendar val ) {
      HSSFCell cell = getcell( sheetNum, x, y );
      if ( cell == null ) {
        return;
      }
      cell.setCellType( HSSFCell.CELL_TYPE_NUMERIC );
      cell.setCellValue( val );
      return;
    }
    void setDateCellValue( short sheetNum, short x, int y, Date val ) {
      HSSFCell cell = getcell( sheetNum, x, y );
      if ( cell == null ) {
        return;
      }
      cell.setCellType( HSSFCell.CELL_TYPE_NUMERIC );
      cell.setCellValue( val );
      return;
    }
    void setShortCellValue( short sheetNum, short x, int y, short val ) {
      HSSFCell cell = getcell( sheetNum, x, y );
      if ( cell == null ) {
        return;
      }
      cell.setCellType( HSSFCell.CELL_TYPE_NUMERIC );
      cell.setCellValue( val );
      return;
    }
    void setFormulaCellValue( short sheetNum, short x, int y, String val ) {
      HSSFCell cell = getcell( sheetNum, x, y );
      if ( cell == null ) {
        return;
      }
      cell.setCellType( HSSFCell.CELL_TYPE_FORMULA );
      cell.setCellFormula( val );
      return;
    }
}

Main.java

package hoge.hoge.com;

import org.apache.poi.hssf.usermodel.HSSFCell;
import hoge.hoge.com.ExcelHandler;

public class Main {

  /**
   * @param args
   */
  public static void main(String[] args) {
    /* 既存エクセルファイルの中身の表示 */
    ExcelHandler handler = new ExcelHandler( "c:\\a.xls" );
    handler.fileopen();
    handler.dispinfo();
    handler.fileclose();
    
    /*
     * 既存エクセルファイルの更新
     */
    handler = new ExcelHandler( "c:\\a.xls" );
    handler.fileopen();
    /* 値の取得と表示 */
    int val = (int) handler.getcell( /* sheetNum */ (short) 0,  /* x */ (short)2, /* y */ 1 ).getNumericCellValue();
    System.out.print("cell value (2,1):" + val);
    /* 値の更新と表示 */
    handler.setNumericCellValue( (short)0, (short)2, 1, val+1);
    val = (int) handler.getcell( (short) 0, (short)2, 1 ).getNumericCellValue();
    System.out.print("cell value (2,1):" + val);
    /* クローズ */
    handler.fileclose();
    
    /*
     * 新規エクセルファイルの作成
     */
    handler = new ExcelHandler( "c:\\c.xls" );
    String [] names = new String[1];
    names[0] = "WorkSheet 1";
    handler.createExcelWorkbook( /* numOfSheets */ 1, /* sheetName */ names );
    /* 値の更新 */
    handler.setStringCellValue( (short)0, (short)0, 0, "品名");
    handler.setStringCellValue( (short)0, (short)1, 0, "個数");
    handler.setStringCellValue( (short)0, (short)2, 0, "単価");
    handler.setStringCellValue( (short)0, (short)3, 0, "合計");
    
    handler.setStringCellValue( (short)0, (short)0, 1, "りんご");
    handler.setNumericCellValue( (short)0, (short)1, 1, 15);
    handler.setNumericCellValue( (short)0, (short)2, 1, 150);
    handler.setFormulaCellValue( (short)0, (short)3, 1, "B2*C2");
    
    /* クローズ */
    handler.fileclose();  
  }
}

テスト実行

c:\a.xls を次のように作成

品名, 単価, 数量
みかん, 30, 20
りんご, 150, 15
バナナ, 100, 6

Main.java を実行して,ファイルの中身が表示されたらOK.