Apache POI version 3.0.1
Jakarta POIを使えばJavaからExcelやWordファイルを操作出来ることは知っていたが、PowerpointやVisioまでを扱えるとは知らなかった。
- POIFS for OLE 2 Documents
- HSSF for Excel Documents
- HWPF for Word Documents
- HSLF for PowerPoint Documents
- HDGF for Visio Documents
- HPSF for Document Properties
- "Apache POI 3.0.1"登場 - 読み込みだけだがVisioへの対応を実現
- http://journal.mycom.co.jp/news/2007/07/10/041/index.html
Apache POI version 3.0.1 の練習1
準備
- Apache POI (http://poi.apache.org/)
- download (http://www.apache.org/dyn/closer.cgi/poi/release/)
- bin を選択
- poi-bin-3.0.1-FINAL-20070705.zip をダウンロード
- jar xvf poi-bin-3.0.1-FINAL-20070705.zip で解凍
- poi-3.0.1-FINAL\poi-3.0.1-FINAL-20070705.jar を使用する
- HSSF Quick Guide (http://poi.apache.org/hssf/quick-guide.html)
- 「// TODO 自動生成されたメソッド・スタブ」を書き換える
HSSFの構成
HSSF(Excel)オブジェクトの操作は、ブック・シート・行・セル・文字列から構成される。Excelの構造を直観的に表しているそうだ・・・
- HSSFWorkbook(ブックを操作するクラス)
- HSSFSheet(シートを操作するクラス)
- HSSFRow(行を操作するクラス)
- HSSFCell(セルを操作するクラス)
- HSSFRichTextString(文字列を操作するクラス)
- HSSFCell(セルを操作するクラス)
- HSSFRow(行を操作するクラス)
- HSSFSheet(シートを操作するクラス)
まずは、Excelファイルの作成
package jp.papa33; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class SamplePoi01 { public static void main(String[] args) { // 新規ワークブックを作成 HSSFWorkbook book = new HSSFWorkbook(); // 新規ワークシートを作成 HSSFSheet sheet1 = book.createSheet("シート1"); HSSFSheet sheet2 = book.createSheet("シート2"); // 作成したシート名を変更 book.setSheetName(1, "シート21"); // 行オブジェクトの作成(行は0からスタート) HSSFRow row1 = sheet1.createRow(0); HSSFRow row2 = sheet2.createRow(1); // セルオブジェクトの作成(セルは0からスタート) HSSFCell cella1 = row1.createCell((short)0); HSSFCell cellb2 = row2.createCell((short)1); // セルに値を設定 HSSFRichTextString richString1 = new HSSFRichTextString("A1のセル"); cella1.setCellValue(richString1); HSSFRichTextString richString2 = new HSSFRichTextString("B2のセル"); cellb2.setCellValue(richString2); // 作成したワークブックを保存 FileOutputStream fileOut = null; try { fileOut = new FileOutputStream("C:\\SamplePoi01.xls"); book.write(fileOut); System.out.println( "Excelファイルの作成が完了しました!"); } catch (FileNotFoundException e) { e.printStackTrace(); return; } catch (IOException e) { e.printStackTrace(); return; } finally { try { fileOut.close(); } catch (Exception e) { e.printStackTrace(); } } } }
戸惑った点
1.エンコーディング設定(ENCODING_UTF_16)は不要になった
org.apache.poi.hssf.usermodel -> HSSFCell -> setEncoding(short encoding)
setEncoding(short encoding)
Deprecated. As of 3-Jan-06 POI now automatically handles Unicode without forcing the encoding.
2.setCellValueするには、HSSFRichTextStringしておく (メソッド setCellValue(String) は型 HSSFCell で使用すべきではありません。)
getString CellValue()
Deprecated. Use the HSSFRichTextString return