zoukankan      html  css  js  c++  java
  • angularJS使用$http请求下载excel表格

    通常下载一个文件

    window.location.href = '文件'

    就能实现下载一个文件的需求。

    但是如果遇到一些特殊的需求,比如说需要在请求头重加一些属性和值,这样window.location.href就不能满足了。但是可以用angularJS自带的$http来请求,并处理应答数据即可:

        $http({
                    url: '/demo/queryFile.json',
                    method: "GET",//接口方法
                    params: {
                        //接口参数
                    },
                    headers: {
                        'Content-type': 'application/json'
                    },
                    responseType: 'arraybuffer' //重点属性,必须设置
                }).success(function (data, status, headers, config) {
                    var blob = new Blob([data], {type: "application/vnd.ms-excel"}); //这里的格式
                    var objectUrl = URL.createObjectURL(blob);
                    //利用浏览器打开URL实现下载
                    var a = document.createElement('a');
                    document.body.appendChild(a);
                    a.setAttribute('style', 'display:none');
                    a.setAttribute('href', objectUrl);
                    var filename="充值记录.xls";
                    a.setAttribute('download', filename);
                    a.click(); //触发点击,下载文件
                    URL.revokeObjectURL(objectUrl);
                }).error(function (data, status, headers, config) {
            });

    接下来画一下重点:

    1.responseType: 'arraybuffer'/'blob',这个属性一定要添加上,不然返回数据类型会出错。

    2.var blob = new Blob([data], {type: "application/vnd.ms-excel"});

    导出文件的格式如下:

    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8
    application/vnd.ms-excel

    按需设置type

    转自:https://blog.csdn.net/qq_34527715/article/details/74285039

  • 相关阅读:
    AngularJS:实现动态添加输入控件功能
    Openfire:XMPP的几种消息类型
    Openfire:重新配置openfire
    Clojure:日期操作方法
    Openfire:通过Servlet群发消息
    Openfire:访问Servlet时绕开Openfire的身份验证
    Clojure:解决selmer模板不刷新的问题
    Intellij Idea 13:运行Clojure的repl环境
    MVC.Net 5:允许保存和输出Html内容
    BAE Flask UEditor 使用七牛云
  • 原文地址:https://www.cnblogs.com/planetwithpig/p/14242123.html
Copyright © 2011-2022 走看看