当前位置: 首页 > 知识库问答 >
问题:

如何在Spring RestController中下载excel文件

裴俊豪
2023-03-14

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

我想从Spring 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);
    }

是否可以从rest控制器返回实际的excel文件,以便用户可以将其下载到计算机上?至于现在控制器返回字节[],但我想返回它的实际文件。我怎样才能做到这一点?

共有3个答案

颛孙昆
2023-03-14

这是我用来下载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();
}
孙帅
2023-03-14

感谢@JAR. JAR. Beans。这是链接:从Spring控制器下载文件

@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
@ResponseBody 
public FileSystemResource getFile(@PathVariable("file_name") String fileName) {
    return new FileSystemResource(myService.getFileFor(fileName)); 
}
韩捷
2023-03-14

您可以使用ByteArrayResources作为文件下载。以下是您修改后的代码片段

    @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);
        }
    }
 类似资料:
  • 我正在使用Postman测试一个视图,该视图应该允许用户下载excel文件。这是视图。。 问题是,当我测试这个视图时,我无法从postman那里获得下载提示。相反,我从邮递员的回复中得到了损坏的数据。以下是一个示例输出: 为什么我不能下载文件?我错过了什么吗?

  • 我有一个API可以返回excel文档作为响应。请求将是一个简单的JSON。 我搜索了谷歌,找到了一些代码库下载文件,我已经在我的应用程序中使用了它,但我得到了一些错误,无法找到它的解决方案。下面是我的代码库。 NameService.ts HTTPService.ts 使用上面的代码库,我得到了以下两个错误,文件没有下载。 null

  • 问题内容: 我有以下网址: 我尝试下载文件: 这产生了一个名为“ test.xls”的文件,但这显然是一个html文件。如果我在firefox中打开了html文件,则打开了一个excel文件,但是如果我在excel中打开了文件,那绝对不是我要找的excel文件。 如果我有一个与上述地址相同的网址,如何使python将excel文件下载为excel文件? 问题答案: 这会将excel文件保存在运行脚

  • 当用户点击下载按钮时,文件应该被下载,而不会在新标签中打开文件预览。如何实现这在反应js?

  • 问题内容: 我收到来自api的文件网址作为响应。当用户单击“下载”按钮时,应在不打开新选项卡的文件预览的情况下下载文件。如何在React JS中实现这一目标? 问题答案: 从前端触发浏览器下载不可靠。 您应该做的是创建一个端点,该端点在被调用时将提供正确的响应头,从而触发浏览器下载。 前端代码只能做很多事情。例如,取决于浏览器,“下载”属性可能只是在新标签中打开文件。 您需要查看的响应标头可能是和