REST方法返回outputStream数据以下载Excel电子表格:
@RequestMapping(value = "/downloadxls", method = RequestMethod.GET)
public @ResponseBody void getRecordsAndExportExcel(@RequestParam("search_param") String students, HttpServletResponse response) {
response.setContentType("application/vnd.ms-excel");
Workbook hssfWorkbook = exportExcelService.getExcelStudents(students);
try {
OutputStream out = response.getOutputStream();
hssfWorkbook.write(out);
out.flush();
out.close();
} catch (IOException e) {
logger.error("Error exporting to excel:" + e);
}
}
我将数据作为字节获取,但在Angular中我试图将其作为Excel电子表格呈现;但它不会下载。我这样做是为了转换:
var blob = new Blob([result.data], {type : 'application/vnd.openxmlformats-officedocument.presentationml.presentation;charset=UTF-8'});
FileSaver.saveAs(blob, "MyData.xls");
请求和响应标头:
Access-Control-Allow-Headers:x-requested-with, content-type
Access-Control-Allow-Methods:GET OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Max-Age:3600
Content-Type:application/vnd.ms-excel;charset=UTF-8
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
X-Application-Context:application:8080
请求标题
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,ms;q=0.6
Connection:keep-alive
Host:localhost:8080
Origin:http://localhost:9000
Referer:http://localhost:9000/
我正在使用Angular从前端进行GET调用并调用后端将数据下载为Excel电子表格,但它无法将输出流转换为blob / excel。如何将Excel电子表格显示为下载?
答案 0 :(得分:0)
我在应用程序中显示Excel工作表的方法是返回要显示的Excel工作表的路径+文件名,然后在新选项卡中使用angular打开链接。
在服务类
中ExportExcel response = new ExportExcel();
response.setPath(excelPath);
return response;
控制器类
Response response = excelService.generateExcel();
return new ResponseEntity<>(response, HttpStatus.OK);
在角度控制器中:
if(response.status === 200){
var excelPath = response.data.path;
var win = window.open(excelPath, '_blank');
if (win) {
//Browser has allowed it to be opened
win.focus();
} else {
//Browser has blocked it
swal(
"Error!",
'Please allow popups for this website',
"error"
);
}
}
试试看是否有效。