今回は整列オプションのデモ (Demonstrates various alignment options) です(一覧)。
Java コード
セルの内容を縦横に整列させるサンプルです。
public static void main(String[] args) throws Exception { Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); Sheet sheet = wb.createSheet(); Row row = sheet.createRow((short) 2); row.setHeightInPoints(30); createCell(wb, row, (short) 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_BOTTOM); createCell(wb, row, (short) 1, CellStyle.ALIGN_CENTER_SELECTION, CellStyle.VERTICAL_BOTTOM); createCell(wb, row, (short) 2, CellStyle.ALIGN_FILL, CellStyle.VERTICAL_CENTER); createCell(wb, row, (short) 3, CellStyle.ALIGN_GENERAL, CellStyle.VERTICAL_CENTER); createCell(wb, row, (short) 4, CellStyle.ALIGN_JUSTIFY, CellStyle.VERTICAL_JUSTIFY); createCell(wb, row, (short) 5, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_TOP); createCell(wb, row, (short) 6, CellStyle.ALIGN_RIGHT, CellStyle.VERTICAL_TOP); } /** * Creates a cell and aligns it a certain way. * * @param wb the workbook * @param row the row to create the cell in * @param column the column number to create the cell in * @param halign the horizontal alignment for the cell. */ private static void createCell(Workbook wb, Row row, short column, short halign, short valign) { Cell cell = row.createCell(column); cell.setCellValue("Align It"); CellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(halign); cellStyle.setVerticalAlignment(valign); cell.setCellStyle(cellStyle); }
セルを生成して整列の設定をする部分をメソッドとして抜き出しています。
PoiBuilder による構築
ビルダーで構築する際も、セルの設定部分をメソッドとして抽出することができます。
@GrabResolver('http://www5.ocn.ne.jp/~coast/repo/') @Grab('org.waman.tools:poi-builder:0.0.3') import org.waman.tools.poi.PoiBuilder // builder をスクリプトのバインディング変数として定義 builder = new PoiBuilder() def workbook = builder.workbook{ // このサンプルでは HSSFWorkbook オブジェクトを生成 sheet{ row(2, heightInPoints:30){ createCell(0, ALIGN_CENTER, VERTICAL_BOTTOM) createCell(1, ALIGN_CENTER_SELECTION, VERTICAL_BOTTOM) createCell(2, ALIGN_FILL, VERTICAL_CENTER) createCell(3, ALIGN_GENERAL, VERTICAL_CENTER) createCell(4, ALIGN_JUSTIFY, VERTICAL_JUSTIFY) createCell(5, ALIGN_LEFT, VERTICAL_TOP) createCell(6, ALIGN_RIGHT, VERTICAL_TOP) } } } def createCell(int column, int halign, int valign){ // cell ノードや cellStyle ノードはビルダー (builder) に対して呼び出す builder.cell(column, cellValue:'Align It', cellStyle:builder.cellStyle(alignment:halign, verticalAlignment:valign)) }
cell ノードや cellStyle ノードはビルダーに対して呼び出す必要があるので、PoiBuilder のインスタンスを builder というバインディング変数として定義して*1、createCell() メソッド中でもそのオブジェクトを参照しています。
作成されるスプレッドシート
- 作者: 関谷和愛,上原潤二,須江信洋,中野靖治
- 出版社/メーカー: 技術評論社
- 発売日: 2011/07/06
- メディア: 単行本(ソフトカバー)
- 購入: 6人 クリック: 392回
- この商品を含むブログ (152件) を見る
*1:groovy.transform.Field アノテーションを使ってスクリプトのフィールドと定義しても OK です。 「@Fieldかわいいよ@Field」を参照。