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);
Author And Source
この問題について(poiでExcelファイルを作成する), 我々は、より多くの情報をここで見つけました https://qiita.com/sheep_LE/items/806ce44a065974157d0a著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .