如何在Spring RestController中下载Excel文件

时间:2018-08-04 10:10:04

标签: java excel spring

我正在使用Apache POI生成 .xlsx 文件。

我想从Spring控制器返回该文件。到目前为止,这是我所做的:

控制器:

@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);
    }

是否可以从rest控制器返回实际的excel文件,以便用户可以将其下载到他的计算机?至于现在控制器返回byte [],但我想将其返回实际文件。我该如何实现?

3 个答案:

答案 0 :(得分:1)

这是我用来下载txt文件的工作代码。 excel文件也应如此。

@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();
}

答案 1 :(得分:1)

您可以使用ByteArrayResource来下载文件。下面是您的修改后的代码段

    @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);
    }

如果您尝试使用apache poi生成excel,请在下面找到代码段

    @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);
        }
    }

答案 2 :(得分:0)

感谢@ JAR.JAR.beans。这是链接: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)); 
}