복붙노트

[SPRING] Spring에서 Excel 다운로드 가능 파일 반환

SPRING

Spring에서 Excel 다운로드 가능 파일 반환

그래서 저는 스프링 컨트롤러를 가지고 있으며, 엑셀 파일을 만들어서 브라우저가 다운로드하도록 리턴하려고합니다.

JEXcelApi를 사용하고 있습니다.

이것은 내 컨트롤러 코드입니다.

@RequestMapping(value="/excel/cols/{colString}/rows/{rowString}/", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<String> exportExcel(HttpServletResponse response,
    @PathVariable List<String> colString,
    @PathVariable List<String> rowString) throws JSONException, IOException, WriteException {
    WritableWorkbook workbook = Workbook.createWorkbook(new File("exported.xls"));
    WritableSheet sheet = workbook.createSheet("Exported",0);
    String[] cols = colString.get(0).split(",");
    String[] rows = rowString.get(0).split(","); 
    for(int i = 0; i < cols.length;i++){
        Label label = new Label(i,0, cols[i]);
        sheet.addCell(label);
    }
    int excelCol = 0;
    int excelRow = 1;
    for(int i = 0; i < rows.length;i++){
        Label label = new Label(excelCol,excelRow, rows[i]);
        sheet.addCell(label);
        excelCol++;
        if((i+1) % cols.length == 0){
            excelCol = 0;
            excelRow++;
        }
    }
    workbook.write();
    workbook.close();
    return null;
}

어떻게해야합니까? 내가 설정할 수있는 콘텐츠 헤더가있는 것 같습니다. 한 가지 방법은 Spring의 추상 Excel보기 클래스를 사용하는 것이지만 더 간단한 방법이 있습니까?

해결법

  1. ==============================

    1.Content-Disposition 헤더를 설정해야합니다.

    Content-Disposition 헤더를 설정해야합니다.

    response.setHeader("Content-disposition","attachment; filename=" + yourFileName);
    

    응답을 OutputStream에 직접 씁니다.

    File xls = new File("exported.xls"); // or whatever your file is
    FileInputStream in = new FileInputStream(xls);
    OutputStream out = response.getOutputStream();
    
    byte[] buffer= new byte[8192]; // use bigger if you want
    int length = 0;
    
    while ((length = in.read(buffer)) > 0){
         out.write(buffer, 0, length);
    }
    in.close();
    out.close();
    

    위는 비교적 오래된 것입니다. 이제 FileSystemResource를 사용하여 ResponseEntity를 구성 할 수 있습니다. ResourceHttpMessageConverter는 위에서 제안한 것처럼 바이트를 복사합니다. Spring MVC는 서블릿 스펙의 인터페이스와 상호 작용하는 것이 아니라 사용자를 위해 더 간단하게 만든다.

  2. from https://stackoverflow.com/questions/18648823/return-excel-downloadable-file-from-spring by cc-by-sa and MIT license