본문으로 바로가기

POI -> 대용량 데이터 Excel 다운로드

category Backend/Spring 2023. 3. 2. 10:35

POI 라이브러리를 사용한 대용량 데이터 Excel 다운로드 소스 정리

private static final int THREAD_POOL_SIZE = 10;

@Transactional(readOnly = true)
public void oralHealthRiskAssessmentDownload(/*String token*/) throws InterruptedException, IOException {
    List<Entity조회> list = entity조회서비스.listAll();

    XSSFWorkbook workbook = new XSSFWorkbook();
    Sheet sheet = workbook.createSheet("시트명");
    ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
    for (int i=0; i< list.size(); i++) {
        int index = i;
        executorService.execute(() -> {
            synchronized (sheet) {
                Entity entity = list.get(index);
                Row row = sheet.createRow(index); // -> 만약 순서 상관 없으면 Row row = sheet.getLastRowNum() + 1; 사용
                int cellIndex = 0;
                Cell idCell = row.createCell(cellIndex++);
                idCell.setCellValue(entity.getId());
                Cell nameCell = row.createCell(cellIndex);
                nameCell.setCellValue(entity.getName());
            }
        });
    }
    executorService.shutdown();
    
    //noinspection ResultOfMethodCallIgnored
    executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

    FileOutputStream outputStream = new FileOutputStream("test.xlsx");
    workbook.write(outputStream);
    workbook.close();
    outputStream.close();
}