zoukankan      html  css  js  c++  java
  • angularJS通过post方法下载excel文件

    • 最近工作中遇到,要使用angularJS的post方法来下载excel的情况。由于请求的url中需要动态拼接签名且要对提交的参数进行封装,在网上找了很久,终于找到了一个可行的。附上代码:
    $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)方法,是防止被浏览器当插件屏蔽弹出连接

    • 对于另一种不需要拼接url及提交参数的get方法:
    function downExcel(this,_url){
    
        $(this).find('a').attr('href',BASE_URL+_url+'?action=dowexcel');
    }
    如果您觉得本文对你有用,不妨帮忙点个赞,为枯燥的学习生活增加一点动力
  • 相关阅读:
    python模块之datetime方法详细介绍
    练习十七:python辨别数据类型
    练习十六:Python日期格式应用(datetime)
    Tkinter的l组件常用属性
    Log4net使用方法
    Thinkphp中在本地测试很好,在服务器上出错,有可能是因为debug缓存的问题
    Git 常见问题
    Linq中的in和not in的使用方法
    网络协议
    WCF传输协议
  • 原文地址:https://www.cnblogs.com/zq123/p/7201378.html
Copyright © 2011-2022 走看看