我有以下控制器下载excel文件。该文件已下载,但是当我打开它时,我得到了#34;该文件已损坏且无法打开。"。我在控制器中做错了什么?
@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);
}
我想添加一个重要细节 我将Swagger接口用于REST API
使用POSTMAN(保存和下载)我能够下载该文件并且它很好。所以似乎问题只是在使用swagger接口
时答案 0 :(得分:1)
我敢打赌你的内容类型与Excel格式不匹配。以下应该足够了:
contentType("application/csv")
无论如何,我建议你看一下网上描述MIME Types的网页。据我所知,格式xsl(x)将匹配最好的所有这些:
application/excel
application/vnd.ms-excel
application/x-excel
application/x-msexcel
答案 1 :(得分:1)
这是我用于xlsx文档的那个:
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet