最近工作中遇到,要使用angularJS的post方法來下載excel的情況。網上找到一個帖子:http://stackoverflow.com/questions/22447952/angularjs-http-post-convert-binary-to-excel-file-and-download ,改動了里面部分代碼搞定。
詳細代碼:
$http.post($rootScope.restful_api.last_output_excel,body_data,{responseType: 'arraybuffer'}).success(function(data){ var blob = new Blob([data], {type: "application/vnd.ms-excel"}); var objectUrl = URL.createObjectURL(blob); var aForExcel = $("<a><span class='forExcel'>下載excel</span></a>").attr("href",objectUrl); $("body").append(aForExcel); $(".forExcel").click(); aForExcel.remove(); })
經驗總結:
1.post的方法里要加responseType: 'arraybuffer'參數,不然下載的excel會亂碼(這點一開始沒注意到,費力好久)
2.使用{type: "application/vnd.ms-excel"}的寫法,可以保存為xls格式的excel文件(兼容老版本)。而使用“application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”則會保存為xlsx
3.使用增加節點調用click方法,而不使用帖子中的window.open(objectUrl)方法,是防止被瀏覽器當插件屏蔽彈出連接