• 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

  • 相关阅读:
    indy Sftp 编程 ftp安全访问
    关于MySql里的字段
    php---魔术方法(__tostring(),__set_state())
    看了这个才发现jQuery源代码不是那么晦涩
    JS的Document属性和方法小结
    JS的Document属性和方法
    原始JS选择器使用方法总结
    docker 镜像配置
    Docker部署SpringBoot项目
    springboot 和spring cloud 博客分享
  • 原文地址:https://www.cnblogs.com/planetwithpig/p/14242123.html
Copyright © 2020-2023  润新知