java - spring下载excel文件

标签 java spring rest api swagger-2.0

我有以下 Controller 来下载 excel 文件。该文件已下载,但当我打开它时,我得到“文件已损坏,无法打开。”。我在 Controller 中做错了什么?

@ApiOperation(value = "export ontology")
@RequestMapping(value = "/export/{ontologyId}", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> exportExcel(@PathVariable Long ontologyId) throws FileNotFoundException {

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Description", "File Transfer");
    headers.add("Content-Disposition", "attachment; filename=pfizer_polish_ontology.xlsx");
    headers.add("Content-Transfer-Encoding", "binary");
    headers.add("Connection", "Keep-Alive");
    headers.setContentType(
            MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));

    File file = new File("C:\\ttt\\pfizer_polish_ontology.xlsx");

    InputStreamResource isr = new InputStreamResource(new FileInputStream(file));
    return ResponseEntity.ok().contentLength(file.length()).headers(headers).body(isr);
}

我想添加一个重要的细节 我正在使用 REST API 的 Swagger 接口(interface)

使用 POSTMAN(保存并下载)我能够下载文件并且很好。所以似乎问题仅在使用 swagger 接口(interface)时出现

最佳答案

这是我用于 xlsx 文档的那个:

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

关于java - spring下载excel文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46036255/

相关文章:

java - 创建一个表并将数据插入数据库不能正常使用 mysql 和 java jdbc

java - 为什么小部件的构造需要上下文?

java - spring web development - 禁用静态内容的缓存

spring - 如何在 Spring 中获取 Session 对象?

spring - RESTful Web 服务、Spring-WS 有效负载或 Spring 3 MVC REST Controller 采用哪种方式?

java - 云 : Amazon, Google、Microsoft - 我可以使用哪种框架?

Java - 构建包含视频/声音/图片/消息的通信器

java - Spring Boot PropertyPlaceholderConfigurer 无法从环境中获得

java - WADL 生成工具

java - JAX-RS 应用程序的初始化