• vue 项目中,后端返回文件流,导出excel


    • 之前写过文件流导出excel,这次直接把上次的代码拿过来复制粘贴,但是导出的表格里面没有数据,只显示undefined。
    • 这是之前的代码
    // api接口页面
    
    // excel导出接口
    export function exportList(query) {
        return request({
        url: '/api/xxx/xxx',                                                   
        method: 'get',
        params: query,
        responseType:'blob' // 重点代码
      })
    }
    
    // vue页面
    
     methods: {
     // 导出excel表格
      exportExcel() {
          exportList()
            .then(res => {
              let data = res.data; // 这里后端对文件流做了一层封装,将data指向res.data即可
              if (!data) {
                return;
              }
              let url = window.URL.createObjectURL(new Blob([data]));
              let a = document.createElement("a");
              a.style.display = "none";
              a.href = url;
              a.setAttribute("download", "excel.xls");
              document.body.appendChild(a);
              a.click(); //执行下载
              window.URL.revokeObjectURL(a.href); //释放url
              document.body.removeChild(a); //释放标签
            })
            .catch(error => {
              console.log(error);
            });
        }
    }
    
    
    • 后来打印发现了问题
    • 上图是打印的结果,发现是blob的size不一样
    • 解决办法,里面添加'charset=utf-8'
    • 上代码
     // 导出excel表格
        exportExcel() {
          exportList()
            .then((res) => {
              var content = res;
              var data = new Blob([content],{type:"application/vnd.ms-excel;charset=utf-8"});  // 重点代码
              var downloadUrl = window.URL.createObjectURL(data);
              var a = document.createElement("a");
              a.href = downloadUrl;
              a.setAttribute("download", "excel.xls");
              a.click();
              window.URL.revokeObjectURL(data);
            })
            .catch((error) => {
              console.log(error);
            });
        },
    
    • 其实我还在 exportList()里面传了参数,为了能简单易懂,传参部分就删掉了-
  • 相关阅读:
    vue的混入mixin拙见
    [附源码]java毕业设计英语知识竞赛报名系统
    Typora如何把图片上传到图床smms.app
    MyMusic 重点实现
    第13章 拷贝控制【C++】
    ESP32(一):使用记录
    BUGKU CTF WE篇(二)
    分别从中序、后续中组成二叉树(likou106)
    为了吃透25个技术栈,这份文档帮我省了大量时间,值得一看
    SAP CO系统配置-获利能力分析
  • 原文地址:https://www.cnblogs.com/masternvshi/p/16914650.html