Spring Boot Controller export an Excel

后端 未结 5 1361
悲&欢浪女
悲&欢浪女 2021-02-06 12:22

I have a java/spring boot application where I want to build an API endpoint that creates and returns a downloadable excel file. Here is my controller endpoint:

@         


        
5条回答
  •  北海茫月
    2021-02-06 12:59

    You have to set the file name to the response header using Content-disposition. Try this

    @GetMapping("/export")
    public ResponseEntity export(HttpServletResponse response) {
            fooService.export(response);      
    }
    

    Change your service method like this

    public Resource export(HttpServletResponse response) throws IOException {
        StringBuilder filename = new StringBuilder("Foo Export").append(" - ")
                                                            .append("Test 1.xlsx");
       return export(filename, response);
    }
    
    private void export(String filename,  HttpServletResponse response) throws IOException {
          try (Workbook workbook = generateExcel()) {
              FileOutputStream fos = write(workbook, filename);
              IOUtils.copy(new FileInputStream(fos.getFD()),               
                                         servletResponse.getOutputStream());//IOUtils is from apache commons io
              response.setContentType("application/vnd.ms-excel");
              response.setHeader("Content-disposition", "attachment; filename=" + filename);
         }catch(Exception e) {
           //catch if any checked exception
         }finally{
            //Close all the streams
         }
    }
    

提交回复
热议问题