加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS通过post方法下载excel文件

发布时间:2020-12-17 09:11:08 所属栏目:安全 来源:网络整理
导读:注明: 第一行的: $rootScope.restful_api.last_output_excel,body_data 这两个值,分别是URL串和post请求的body。其他代码不用变,即可使用。 原文链接:http://www.cnblogs.com/xujanus/p/5985644.html 最近工作中遇到,要使用angularJS的post方法来下载e

注明:

第一行的:

$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)方法,是防止被浏览器当插件屏蔽弹出连接

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读