Vue3 导出 txt 和 excel

一:  在响应拦截器对响应数据进行处理

 代码如下:

if (response.data instanceof ArrayBuffer) {
  return response;
}
if (response.data instanceof Blob) {
  return response;
}

二: 必须设置 响应类型为blob

 代码如下:

responseType: 'blob',

三: 接口调用下载导出的方法

代码如下: 

// 下载导出 txt Excel
const handleDownload = (id: string, type: string, fileName: string) => {
  reportsDownload({ id: id }).then((res) => {
    console.log("res Blob", res);
    const blob =
      type === "excel"
        ? new Blob([res.data], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          })
        : new Blob([res.data], { type: "text/plain" }); // 转换为二进制
    const blobUrl = URL.createObjectURL(blob); // 转换为二进制 的链接
    const link = document.createElement("a"); // 创建a标签
    link.href = blobUrl; // 下载链接
    link.download = fileName; // 下载的文件名
    document.body.appendChild(link);
    link.click();
  });
};

这里出现个问题: 导出txt文件类型后再导出excel类型的文件,但是会自动变成txt 类型的

看看 link 是不是对应的类型,会有影响导出的文件类型的

四:不调用接口,前端将表格数据导出表格为 excel

1. 给 el-table 添加 ref

2. 方法如下:

    exportToExcel() {
      const table = this.$refs.table.$el;
      const workbook = XLSX.utils.table_to_book(table, { raw: true });
      const wbout = XLSX.write(workbook, { bookType: "xlsx", type: "array" });
      let tableName = ''; // 自定义名字
      tableName ? tableName + ".xlsx" : "表格.xlsx";
      this.downloadExcel(wbout, tableName);
    },

    downloadExcel(buffer, filename) {
      const blob = new Blob([buffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
      const link = document.createElement("a");
      const url = URL.createObjectURL(blob);
      link.href = url;
      link.setAttribute("download", filename);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    },

                                                                                                                   记录,做专属的备忘录!

                                                                                                                                           —— 安夏

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值