@Slf4j
public class SheetServiceTest {
@Test
public void generateWorkBook() throws Exception {
List<Dump> dumps = generateDump(10, "a", "b", "c", "d");
String excelFileName = "test.xls";
String sheetname = "send-check-1";
Workbook workbook = new HSSFWorkbook();
workbook.createSheet(sheetname);
Sheet sheet = workbook.getSheet(sheetname);
int size = dumps.size();
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("A column");
headerRow.createCell(1).setCellValue("B column");
headerRow.createCell(2).setCellValue("C column");
headerRow.createCell(3).setCellValue("D column");
for (int rownum = 0; rownum < size; rownum++) {
Row row = sheet.createRow(rownum + 1);
row.createCell(0).setCellValue(dumps.get(rownum).getA());
row.createCell(1).setCellValue(dumps.get(rownum).getB());
row.createCell(2).setCellValue(dumps.get(rownum).getC());
row.createCell(3).setCellValue(dumps.get(rownum).getD());
}
generateExcel(Paths.get(excelFileName).toString(), workbook);
assertThat(Paths.get(excelFileName).toFile().exists()).isTrue();
assertThat(workbook.getSheet(sheetname)).isNotNull();
assertThat(sheet.getLastRowNum()).isEqualTo(10);
assertThat(sheet.getRow(sheet.getFirstRowNum()).getCell(0).toString()).isEqualTo("A column");
assertThat(sheet.getRow(sheet.getLastRowNum()).getCell(0).toString()).isEqualTo("a9");
Paths.get(excelFileName).toFile().delete();
}
private List<Dump> generateDump(int it, String a, String b, String c, String d) {
List<Dump> dumps = Lists.newArrayList();
for (int i = 0; i < it; i++) {
dumps.add(Dump.builder().a(a + "" + i).b(b + "" + i).c(c + "" + i).d(d + "" + i).build());
}
return dumps;
}
private void generateExcel(String filePath, Workbook workbook) {
log.debug("generate excel: {}", filePath);
try (FileOutputStream fileOut = new FileOutputStream(filePath);) {
workbook.write(fileOut);
} catch (Exception e) {
log.error("Occur exception: {}", e);
}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public static class Dump {
String a;
String b;
String c;
String d;
}
}