Jakarta POI 3.7 セルの生成・値の設定

3.7にバージョンアップされていると言うことで心機一転、サンプルコードを片手に着手してみようかと。年末のこんな時期に(笑)

実行サンプルもりもりで行こう。まずは値の設定から。

// Rowの生成・値の設定(インデックスは0始まり).
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue(1);

// 若しくは1行でこういう設定方法も可能.
row.createCell(1).setCellValue(true);                       // Boolean
Calendar calendar = Calendar.getInstance();
row.createCell(2).setCellValue(calendar);                   // Calendar型
row.createCell(3).setCellValue(new Date());                 // Date型
row.createCell(4).setCellValue(new Double(3.14159265d));    // Double型
CreationHelper creationHelper = workbook.getCreationHelper();
row.createCell(5).setCellValue(creationHelper.createRichTextString("日本語データ?"));   // RichTextString型
row.createCell(6).setCellValue("日本語データ?");           // String型
row.createCell(7).setCellValue(XSSFCell.CELL_TYPE_ERROR);

設定可能な要素としてRichTextString型とString型があるようですが、両者の違いはどの辺にあるんでしょうねぇ?

Rich text unicode string. These strings can have fonts applied to arbitary parts of the string.
(リッチテキストのUnicode文字列を指定します。これらの文字列は文字列の任意の部分に適用されるフォントを持ちます。)

とありますが…いまいち良く分かりません。(^_^;)普通に文字列出力するだけなら同じなのかな?

日付型のデータなどは、フォーマットを指定することも可能。

// 日付型のデータ設定(フォーマット指定有)
row.createCell(8).setCellValue(new Date());
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy/mm/dd hh:mm:ss"));

// CellStyleをCellに適用
row.getCell(2).setCellStyle(cellStyle);
row.getCell(3).setCellStyle(cellStyle);
row.getCell(8).setCellStyle(cellStyle);

実行例。