美文网首页
vue项目中导出Excel文件

vue项目中导出Excel文件

作者: 辉色星空下 | 来源:发表于2023-05-18 09:39 被阅读0次

    由后台返回二进制流
    然后在接口调用的时候在接口中加入
    responseType: "blob"

    如: image.png
    将下列方法添加到你的util文件中然后在你的vue文件中直接导入使用
    import { exportFile } from "@/utils/utils";
    

    调用如图所示


    image.png
    /**
     * 文件导出
     * @param param Blob二进制流
     * @param param header 获取文件名称
     * @returns
     */
    export const exportFile = function(res, headers) {
      if (Object.prototype.toString.call(res) === "[object Blob]") {
        const fileReader = new FileReader();
        fileReader.onload = function(e) {
          try {
            const blob = new Blob([res]);
            const fileName = headers["content-disposition"].match(
              /filename="(\S*)"/
            )
              ? headers["content-disposition"].match(/filename="(\S*)"/)[1]
              : headers["content-disposition"].match(/filename="?(\S*)"?/)[1];
            // console.log(fileName);
            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
              navigator.msSaveBlob(blob, fileName);
            } else {
              // return;
              const elink = document.createElement("a");
              elink.download = decodeURIComponent(fileName);
              elink.style.display = "none";
              elink.href = URL.createObjectURL(blob);
              document.body.appendChild(elink);
              elink.click();
              URL.revokeObjectURL(elink.href); // 释放URL 对象
              document.body.removeChild(elink);
            }
          } catch (err) {
            console.log(err);
          }
        };
        fileReader.readAsText(res);
        Message({
          type: "success",
          message: "导出成功"
        });
      }
    };
    

    相关文章

      网友评论

          本文标题:vue项目中导出Excel文件

          本文链接:https://www.haomeiwen.com/subject/vfpwsdtx.html