angularJS經過post方法下載excel文件

最近工做中遇到,要使用angularJS的post方法來下載excel的狀況。網上找到一個帖子:http://stackoverflow.com/questions/22447952/angularjs-http-post-convert-binary-to-excel-file-and-download ,改動了裏面部分代碼搞定。angularjs

詳細代碼:api

            $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會亂碼(這點一開始沒注意到,費力很久)restful

2.使用{type: "application/vnd.ms-excel"}的寫法,能夠保存爲xls格式的excel文件(兼容老版本)。而使用「application/vnd.openxmlformats-officedocument.spreadsheetml.sheet」則會保存爲xlsxapp

3.使用增長節點調用click方法,而不使用帖子中的window.open(objectUrl)方法,是防止被瀏覽器當插件屏蔽彈出鏈接post

相關文章
相關標籤/搜索