zoukankan      html  css  js  c++  java
  • 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)方法,是防止被浏览器当插件屏蔽弹出连接

    
    
  • 相关阅读:
    [转载]Nginx 常见应用技术指南
    【转载】Memcached Tip 2:Session同步
    【转载】大规模网站架构实战之体系结构
    【转载】3种Nginx防盗链的方法
    poj2390
    poj2395
    poj2393
    poj2209
    poj2392
    爱我更多,好吗?
  • 原文地址:https://www.cnblogs.com/xujanus/p/5985644.html
Copyright © 2011-2022 走看看