Spring Boot Controller export an Excel

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

    You can use this :

     headers.add("Content-Disposition", "attachment; filename=NAMEOFYOURFILE.xlsx");
    ByteArrayInputStream in = fooService.export();
    return ResponseEntity
                .ok()
                .headers(headers)
                .body(new InputStreamResource(in));
    

    It will download the Excel file when you call this endpoint.

    In your export method in your service, you have to return something like that :

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ByteArrayInputStream(out.toByteArray());
    

提交回复
热议问题