Apache POI メモリ消費量が増えやすいし、今となっては使いにくい。
Excel の場合、セルのスタイル設定は今のメソッドは、まあ許すとして
セルの値セットや、スタイル適用のメソッドが実行後のセルを返してくれれば、数珠つなぎにメソッド呼べるのに。。
そこで思いついたのは、Java8 からの java.util.Optional で括って ifPresent の Consumer を使う方法
邪道かもしれないけど。
こんな風に。。。
try(InputStream is = new FileInputStream("sample.xlsx"); FileOutputStream out = new FileOutputStream(new File("test.xlsx"));){ XSSFWorkbook book = new XSSFWorkbook(is); XSSFSheet sheet = book.getSheetAt(0); XSSFCellStyle style = book.createCellStyle(); style.setBorderTop(BorderStyle.THIN); style.setTopBorderColor(IndexedColors.BLACK.index); style.setBorderBottom(BorderStyle.THIN); style.setBottomBorderColor(IndexedColors.BLACK.index); style.setBorderRight(BorderStyle.THIN); style.setRightBorderColor(IndexedColors.BLACK.index); style.setBorderLeft(BorderStyle.THIN); style.setLeftBorderColor(IndexedColors.BLACK.index); style.setAlignment(CellStyle.ALIGN_CENTER); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER ); IntStream.rangeClosed(0, 8).boxed().forEach(rownum->{ XSSFRow row = sheet.createRow(rownum); IntStream.rangeClosed(0, 4).boxed().forEach(columnIndex->{ Optional.of(row.createCell(columnIndex)).ifPresent(cell->{ cell.setCellValue( rownum + "-" + columnIndex ); cell.setCellStyle(style); }); }); }); book.write(out); }catch(Exception e){ e.printStackTrace(); }