Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download an excel file in Spring RestController

Tags:

java

spring

excel

I am using Apache POI to generate .xlsx file.

I would like to return that file from Spring controller. Here's what I've done so far:

Controller:

@RequestMapping(method = RequestMethod.GET)
    public HttpEntity<byte[]> createExcelWithTaskConfigurations(HttpServletResponse response) throws IOException {
        byte[] excelContent = excelService.createExcel();

        HttpHeaders header = new HttpHeaders();
        header.setContentType(new MediaType("application", "vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        header.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=my_file.xls");
        header.setContentLength(excelContent.length);

        return new HttpEntity<>(excelContent, header);
    }

Is it possible to return actual excel file from rest controller so user can download it to his computer ? As for now controller returning byte[] but I would like to return it actual file. How can I achieve that ?

like image 537
Martin Čuka Avatar asked Aug 04 '18 10:08

Martin Čuka


3 Answers

You can use ByteArrayResource to download as a file. Below is the modified code snippet of yours

    @GetMapping(value="/downloadTemplate")
    public HttpEntity<ByteArrayResource> createExcelWithTaskConfigurations() throws IOException {
        byte[] excelContent = excelService.createExcel();

        HttpHeaders header = new HttpHeaders();
        header.setContentType(new MediaType("application", "force-download"));
        header.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=my_file.xlsx");


        return new HttpEntity<>(new ByteArrayResource(excelContent), header);
    }

If you are trying to generate excel using apache poi, please find the code snippet below

    @GetMapping(value="/downloadTemplate")
    public ResponseEntity<ByteArrayResource> downloadTemplate() throws Exception {
        try {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            XSSFWorkbook workbook = createWorkBook(); // creates the workbook
            HttpHeaders header = new HttpHeaders();
            header.setContentType(new MediaType("application", "force-download"));
            header.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=ProductTemplate.xlsx");
            workbook.write(stream);
            workbook.close();
            return new ResponseEntity<>(new ByteArrayResource(stream.toByteArray()),
                    header, HttpStatus.CREATED);
        } catch (Exception e) {
            log.error(e.getMessage());
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
like image 166
vettrivel18 Avatar answered Sep 16 '22 15:09

vettrivel18


This is working code I have used to download txt file. Same should do for excel file as well.

@GetMapping("model")
public void getDownload(HttpServletResponse response) throws IOException {


    InputStream myStream = your logic....

    // Set the content type and attachment header.  for txt file
    response.addHeader("Content-disposition", "inline;filename=sample.txt");
    response.setContentType("txt/plain");

    // xls file
    response.addHeader("Content-disposition", "attachment;filename=sample.xls");
    response.setContentType("application/octet-stream");

    // Copy the stream to the response's output stream.
    IOUtils.copy(myStream, response.getOutputStream());
    response.flushBuffer();
}
like image 22
MyTwoCents Avatar answered Sep 19 '22 15:09

MyTwoCents


Thanks to @ JAR.JAR.beans. Here is the link: Downloading a file from spring controllers

@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
@ResponseBody 
public FileSystemResource getFile(@PathVariable("file_name") String fileName) {
    return new FileSystemResource(myService.getFileFor(fileName)); 
}
like image 42
Mafuj Shikder Avatar answered Sep 17 '22 15:09

Mafuj Shikder