table 导出表格 Excel

在请求中需要设置 responseType: blob

javascript 复制代码
export const requestExport = (api, method, params = {}, config) => {
    const apiToken = localStorage.getItem('token');
    const data = method === 'GET' ? 'params' : 'data';
    let headers = {
        'BackServer-Token': `${apiToken}`,
    };
    if (config?.headers) {
        headers = {
            ...headers,
            ...config.headers,
        };
    }
    
    return new Promise((resolve, reject) => {
    axios({
        ...config,
        url: baseUrl + api,
        method,
        [data]: params,
        headers,
        responseType: 'blob'
        })
    .then(res => {
        if (res.status === 200) {
        resolve(res)
        }
    })
    .catch(error => {
    ElMessage({
        message: '服务器繁忙请稍后重试!',
        type: 'error'
    })
    reject(error);
  });
 });
};

并且核心在于函数:

javascript 复制代码
export const download = (fileName, res) => {
  const blob = new Blob([res.data],{type: 'application/vnd.ms-excel'});
  if ("download" in document.createElement("a")) {
    const elink = document.createElement("a");
    elink.download = 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);
 }
}

在页面中发送请求:

在 element 的表格组件中对选中的行进行导出

javascript 复制代码
const exportTags = async () => {
  if (selectId.length < 1) {
    ElMessage.error('至少选择一个标签!')
  } else {
    await exportTag({'tag_ids': selectId}).then(res => {
      download('标签列表.xlsx', res)
      selectId = []
    }, (err) => {
      ElMessage.error('导出失败!')
    })
  }
}
相关推荐
m0_7381207213 分钟前
应急响应——知攻善防Web-3靶机详细教程
服务器·前端·网络·安全·web安全·php
hh随便起个名6 小时前
力扣二叉树的三种遍历
javascript·数据结构·算法·leetcode
我是小路路呀7 小时前
element级联选择器:已选中一个二级节点,随后又点击了一个一级节点(仅浏览,未确认选择),此时下拉框失去焦点并关闭
javascript·vue.js·elementui
程序员爱钓鱼7 小时前
Node.js 编程实战:文件读写操作
前端·后端·node.js
PineappleCoder7 小时前
工程化必备!SVG 雪碧图的最佳实践:ID 引用 + 缓存友好,无需手动算坐标
前端·性能优化
JIngJaneIL8 小时前
基于springboot + vue古城景区管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
敲敲了个代码8 小时前
隐式类型转换:哈基米 == 猫 ? true :false
开发语言·前端·javascript·学习·面试·web
澄江静如练_8 小时前
列表渲染(v-for)
前端·javascript·vue.js
JustHappy9 小时前
「chrome extensions🛠️」我写了一个超级简单的浏览器插件Vue开发模板
前端·javascript·github