【问题标题】:How to download an excel file in Spring RestController如何在 Spring RestController 中下载 excel 文件
【发布时间】:2018-08-04 10:10:03
【问题描述】:

我正在使用 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[] 但我想返回实际文件。我怎样才能做到这一点?

【问题讨论】:

  • 您可以使用标准的 apache commons utils 来下载文件。 Similar question.
  • 是的,我已经读过了。我试图从创建 excel 的服务返回 InpurtStream 然后使用 IOUtils.copy(targetStream, response.getOutputStream());在控制器中,但它仅以不可读的字符“打印”响应。我想实际从控制器下载文件。到目前为止没有运气
  • that 怎么样?这个问题也和你很接近。

标签: java excel spring


【解决方案1】:

您可以使用ByteArrayResource 作为文件下载。下面是你修改后的代码sn-p

    @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,请在下面找到代码sn-p

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

【讨论】:

  • 感谢 Excel / POI 示例,很棒的解决方案 imo,因为它非常适合 Spring 的做事方式。仅供参考,对于任何使用它的人,通过“与 Spring 配合”我的意思是它返回 Spring 的 ResponseEntity,并且下载 wok 的类来自 org.springframework.core.io 和 org.springframework.http 包。
  • 什么是 XSSFWorkbook workbook = createWorkBook();??
【解决方案2】:

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

【讨论】:

  • 嗯,我的服务是什么?
【解决方案3】:

这是我用来下载 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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    相关资源
    最近更新 更多