前端blob方式导出Excel

封装axios:

import axios from "axios";
const server = axios.create({
  timeout: 20000,
  withCredentials: true,
  headers: {
    "Content-Type": "application/json; charset=utf-8"
  },
});
// 请求拦截器
server.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    let userinfo = JSON.parse(window.localStorage.getItem("userinfo"));

    if (userinfo) {
      config.headers.Authorization = userinfo.token;
    }
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);
// 响应拦截
server.interceptors.response.use(
  function (response) {
    // 如果返回的状态码为200,说明接口请求成功,可以正常拿到数据否则的话抛出错误
    if (response.status === 200) { 
      // 未登录或者token过期
      if (response.data.err === 1) {    
        localStorage.removeItem("userinfo");
        setTimeout(() => {
          router.push("/login");
        }, 1000);
      } else if (response.data.err === 10) {
        setTimeout(() => {
          router.push("/nopower");
        }, 1000);
      }
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  function (error) {
    if (error.response.status) {
      switch (error.response.status) {
        case 401:
          break;
        case 404:
          Message.error("网络请求不存在");
          break;
        // 其他错误,直接抛出错误提示
        case 500:
          if (error.response.data.err === 1) {
            localStorage.removeItem("userinfo");
            setTimeout(() => {
              router.push("/login");
            }, 1000);
          }
          break;
        default:
          Message.error(error.response.data.msg);
      }
      return Promise.reject(error.response.data.msg);
    }
  }
);
server.adornUrl = (actionName) => {
  // 非生产环境 && 开启代理, 接口前缀统一使用[/proxyApi/]前缀做代理拦截!
  return "/api" + actionName;
};
export default server;

请求接口:

import server from "@/api/request";
export const exportLogin = async (data) => await server.post("/farm/sys/log/exportLogin", data, { responseType: "blob"})

主要代码:

exportLogin({
  pn: this.currentPage,
  ps: this.pageSize,
}).then((res) => {
  this.exportLoading = false;
  const fileName = `名字${+new Date()}.xlsx`;
  const blob = new Blob([res.data], {
    type: "application/vnd.ms-excel;charset=utf-8",
  });
  const link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = fileName;
  link.click();
  URL.revokeObjectURL(link.href);
  })
  .catch((err) => {
  this.$message.error({ message: err });
  this.exportLoading = false;
  });

你可能感兴趣的:(前端blob方式导出Excel)