Java 如何在 Spring RestController 中下载 excel 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51684550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to download an excel file in Spring RestController
提问by Martin ?uka
I am using Apache POI to generate .xlsxfile.
我正在使用 Apache POI 生成.xlsx文件。
I would like to return that file from Spring controller. Here's what I've done so far:
我想从 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);
}
Is it possible to return actual excel file from rest controller so user can download it to his computer ? As for now controller returning byte[] but I would like to return it actual file. How can I achieve that ?
是否可以从 rest 控制器返回实际的 excel 文件,以便用户可以将其下载到他的计算机上?至于现在控制器返回 byte[] 但我想返回它的实际文件。我怎样才能做到这一点?
回答by MyTwoCents
This is working code I have used to download txt file. Same should do for excel file as well.
这是我用来下载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();
}
回答by Mafuj Shikder
Thanks to @ JAR.JAR.beans. Here is the link: Downloading a file from spring controllers
感谢@ JAR.JAR.beans。这是链接:从弹簧控制器下载文件
@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
@ResponseBody
public FileSystemResource getFile(@PathVariable("file_name") String fileName) {
return new FileSystemResource(myService.getFileFor(fileName));
}
回答by vettrivel18
You can use ByteArrayResource
to download as a file. Below is the modified code snippet of yours
您可以使用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);
}
If you are trying to generate excel using apache poi, please find the code snippet below
如果您尝试使用 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);
}
}