今回はフォント (Working with fonts) です(一覧)。
Java コード
フォントを設定する Java コード。
Workbook wb = new HSSFWorkbook(); Sheet sheet = wb.createSheet("new sheet"); // Create a row and put some cells in it. Rows are 0 based. Row row = sheet.createRow(1); // Create a new font and alter it. Font font = wb.createFont(); font.setFontHeightInPoints((short)24); font.setFontName("Courier New"); font.setItalic(true); font.setStrikeout(true); // Fonts are set into a style so create a new one to use. CellStyle style = wb.createCellStyle(); style.setFont(font); // Create a cell and put a value in it. Cell cell = row.createCell(1); cell.setCellValue("This is a test of fonts"); cell.setCellStyle(style);
フォントはセルに直接設定できるわけではなく、CellStyle を介して設定します。 また、Font オブジェクトは Workbook#createFont() メソッドによって生成します。
PoiBuilder による構築
PoiBuilder によってフォントを設定するサンプル。 PoiBuilder は Apache POI と同じオブジェクト・モデルなので、フォントは CellStyle を介して設定します。
@GrabResolver('http://www5.ocn.ne.jp/~coast/repo/') @Grab('org.waman.tools:poi-builder:0.0.4') import org.waman.tools.poi.PoiBuilder def workbook = new PoiBuilder().workbook{ sheet('new sheet'){ row(1){ // Font オブジェクトを生成 def myFont = font(fontHeightInPoints:24, fontName:'Courier New', italic:true, strikeout:true) // cellStyle を介してセルにフォントを設定 cell(1, cellValue:'This is a test of fonts', cellStyle:cellStyle(font:myFont)) } } }
font ノードは Workbook#createFont() メソッドを呼び出しているので、各ノードごとに Font インスタンスを生成します。 なので、複数のセルに同じフォントを設定する場合はインスタンスを使い回しましょう。 ちなみに、今のところ cellStyle ノードも cell ノードの子ノードでないなら Workbook#createStyle() メソッドによってインスタンスを生成します(属性の場合も生成します)。
作成されるスプレッドシート

見やすさのためにセルの大きさは適当に変えてます。

- 作者: 関谷和愛,上原潤二,須江信洋,中野靖治
- 出版社/メーカー: 技術評論社
- 発売日: 2011/07/06
- メディア: 単行本(ソフトカバー)
- 購入: 6人 クリック: 392回
- この商品を含むブログ (152件) を見る