倭マン's BLOG

くだらない日々の日記書いてます。 たまにプログラミング関連の記事書いてます。 書いてます。

PoiBuilder で Quick Guide (7) : 境界を扱う

今回は境界を扱う (Working with borders) です(一覧)。

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 cell and put a value in it.
    Cell cell = row.createCell(1);
    cell.setCellValue(4);

    // Style the cell with borders all around.
    CellStyle style = wb.createCellStyle();
    style.setBorderBottom(CellStyle.BORDER_THIN);
    style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderLeft(CellStyle.BORDER_THIN);
    style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
    style.setBorderRight(CellStyle.BORDER_THIN);
    style.setRightBorderColor(IndexedColors.BLUE.getIndex());
    style.setBorderTop(CellStyle.BORDER_MEDIUM_DASHED);
    style.setTopBorderColor(IndexedColors.BLACK.getIndex());
    cell.setCellStyle(style);

生成したセルの上下左右のボーダーの線種と色を設定しています。 これは辟易しますねぇ。

PoiBuilder による構築


PoiBuilder でも CellStyle オブジェクトを生成してボーダーを設定するのは同じです。 ただ、Map として設定できるので見やすさはかなり改善されていると思います:

@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){
            def style = cellStyle(borderBottom:BORDER_THIN, bottomBorderColor:BLACK,
                                        borderLeft:BORDER_THIN, leftBorderColor:GREEN,
                                        borderRight:BORDER_THIN, rightBorderColor:BLUE,
                                        borderTop:BORDER_MEDIUM_DASHED, topBorderColor:BLACK)
            cell(1, cellValue:4, cellStyle:style)
        }
    }
}

CellStyle に定義されている定数(public static final なフィールド)である BORDER_XXXX や色を表すオブジェクト IndexedColors に定義されている定数*1が PoiBuilder のプロパティとしてセットされているので、import 文や定数が定義されている型の参照などを書く必要もありません。 これで結構コンパクトに設定が記述できるようになったと思います。

作成されるスプレッドシート





ボーダーを設定しているセル 【B2】 以外にもその上のセル 【B1】 のボーダーが変更されていますが、これはこのセルのインスタンスが生成されていないためのようで、事前に 【B1】 セルを生成しておけばこの設定は行われません。
プログラミングGROOVY

プログラミングGROOVY

*1:こちらはその index プロパティをプロパティ値としてセットしています。