Return Excel downloadable file from Spring

前端 未结 1 1887
情歌与酒
情歌与酒 2021-01-02 07:50

So I have a Spring controller, and I\'d like to create an Excel file and return it so that it is downloaded by the browser.

I\'m using JEXcelApi.

This is m

相关标签:
1条回答
  • 2021-01-02 08:18

    You need to set the Content-Disposition header.

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

    and write your bytes directly to the response 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();
    

    The above is relatively old. You can construct a ResponseEntity with FileSystemResource now. A ResourceHttpMessageConverter will then copy the bytes, as I have suggested above, for you. Spring MVC makes it simpler for you rather than having you interact with interfaces from the Servlet specification.

    0 讨论(0)
提交回复
热议问题