angularJS通過post方法下載excel文件


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

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM