1. 程式人生 > >AngularJS通過post方法下載excel檔案

AngularJS通過post方法下載excel檔案

註明:

第一行的:

$rootScope.restful_api.last_output_excel,body_data

這兩個值,分別是URL串和post請求的body。其他程式碼不用變,即可使用。



原文連結:http://www.cnblogs.com/xujanus/p/5985644.html

最近工作中遇到,要使用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)方法,是防止被瀏覽器當外掛遮蔽彈出連線