ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • spring webflux mono excel dowonlad(poi 라이브러리)
    Spring/spring boot 및 기타 2023. 6. 27. 14:55

    excel poi 라이브러리

     <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.2.3</version>
    </dependency>

    spring webflux 에서는 HttpServletResponse 를 사용하지 않아 header 에 xlsx 정보를 넣어주는부분에서 spring 일반 샘플대로 하면 오류가 생길 것이다. 
    HttpHeaders 에 set 해주고 Mono.just 에 headers 를 세팅해주면 된다. 

    import org.apache.poi.ss.usermodel.*;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    import org.springframework.core.io.ByteArrayResource;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import reactor.core.publisher.Mono;
    
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    
    @RestController
    public class ExcelController {
    
        @GetMapping("/download-excel")
        public Mono<ResponseEntity<ByteArrayResource>> downloadExcel() {
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Sheet1");
    
            // Create some sample data
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("Name");
            headerRow.createCell(1).setCellValue("Email");
    
            Row dataRow = sheet.createRow(1);
            dataRow.createCell(0).setCellValue("John Doe");
            dataRow.createCell(1).setCellValue("john.doe@example.com");
    
            // Generate Excel file bytes
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            try {
                workbook.write(outputStream);
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            // Set up the HTTP response headers
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "data.xlsx");
    
            // Create a ByteArrayResource from the file bytes
            ByteArrayResource resource = new ByteArrayResource(outputStream.toByteArray());
    
            // Return the response entity with the file bytes and headers
            return Mono.just(ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(outputStream.size())
                    .body(resource));
        }
    }

     

    반응형

    댓글

Designed by Tistory.