Spring Boot Controller export an Excel

后端 未结 5 1290
悲&欢浪女
悲&欢浪女 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:38

    Since you are using ByteArrayResource, you can use the below controller code assuming that the FooService is autowired in the controller class.

    @RequestMapping(path = "/download_excel", method = RequestMethod.GET)
    public ResponseEntity download(String fileName) throws IOException {
    
    ByteArrayResource resource = fooService.export(fileName);
    
    return ResponseEntity.ok()
            .headers(headers) // add headers if any
            .contentLength(resource.contentLength())
            .contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
            .body(resource);
    }
    

提交回复
热议问题