poiでExcelファイルを作成する


poiでテンプレートファイルを使ってExcelファイルを作成する方法の覚書。

1.テンプレートファイルを読み込む

File file = new File("C:\\tmp\\templates\\templates.xml");
Workbook workbook = null;

try (InputStream is = new ByteArrayInputStream(
        Files.readAllBytes(file.toPath()));) {
    workbook = WorkbookFactory.create(is);
} catch (IOException e) {
    e.printStackTrace();
}

2.ファイルを出力する

FileOutputStream fout = null;
try {
    fout = new FileOutputStream("C:\\tmp\\");
    workbook.write(fout);
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (fout != null) {
        try {
            fout.close();
        } catch (IOException e) {
        }
    }
}

3.セルに値を設定する
セルを指定するためのインデックスは0開始である点に注意。
また、rowまたはcellがNULLの場合、設定時にNullPointerExceptionが発生するため、必ずcreateRow/createCellを行うこと。

Sheet sheet = workbook.getSheet("Sheet1");
getCell(sheet, 0, 0).setCellValue("test");

private Cell getCell(Sheet sheet, int rowIndex, int colIndex) {

    Row row = sheet.getRow(rowIndex);

    if (row == null) {
        row = sheet.createRow(rowIndex);
    }

    Cell cell = row.getCell(colIndex);

    if (cell == null) {
        cell = row.createCell(colIndex);
    }

    return cell;

}

4.シートを削除する
こちらもインデックスは0開始。
Sheet1を削除したい場合は0、Sheet2を削除したい場合は1を設定する。

workbook.removeSheetAt(0);

5.印刷範囲の指定
インデックスは以下略。
第一引数:印刷範囲を設定するシートのインデックス
第二引数:印刷範囲開始位置のカラムのインデックス
第三引数:印刷範囲終了位置のカラムのインデックス
第四引数:印刷範囲開始位置の行のインデックス
第五引数:印刷範囲終了位置の行のインデックス
この例だと、Sheet1のA1セルのみが印刷範囲に指定される。

workbook.setPrintArea(0, 0, 1, 0, 1);