vue项目中导出Excel文件

2023-05-18  本文已影响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: "导出成功"
    });
  }
};
上一篇下一篇

猜你喜欢

热点阅读