前端之家收集整理的这篇文章主要介绍了
AngularJS+Jersey下载excel,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_
502_0@
AngularJS代码:
@H_
502_0@
$scope.testDownload =function () {
@H_
502_0@
$http.post("rest/excel/down",$scope.req,{responseType:'arraybuffer'}).success(function (data) {
@H_
502_0@
varblob =new Blob([data],{type:"application/vnd.ms-excel"});
@H_
502_0@
varfileName ="ttt2.xls";
@H_
502_0@
vara = document.createElement("a");
@H_
502_0@
document.body.appendChild(a);
@H_
502_0@
a.download = fileName;
@H_
502_0@
a.href = URL.createObjectURL(blob);
@H_
502_0@
a.click();
@H_
502_0@
}).error(function (data) {
@H_
502_0@
$("#serverErrorModal").modal({show:true});
@H_
502_0@
});
}
注意post的方法里要加responseType: 'arraybuffer'参数,不然下载的excel会乱码!!!
使用{type:"application/vnd.ms-excel"}的写法,可以保存为xls格式的excel文件(兼容老版本)。而使用“application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”则会保存为xlsx。
Server端示例代码:
@POST
@H_
502_0@
@Path("down")
@H_
502_0@
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@H_
502_0@
publicbyte[] downloadExcel(@Context HttpServletResponse response)throws IOException {
@H_
502_0@
//.....略
@H_
502_0@
File file1= new File("D:/excel/ttt2.xls");
@H_
502_0@
byte[] aa = Files.toByteArray(file1);
@H_
502_0@
return aa;
}