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('导出失败!')
    })
  }
}
相关推荐
XiaoYu20028 分钟前
第11章 LangChain
前端·javascript·langchain
霉运全滚蛋好运围着转35 分钟前
启动 Taro 4 项目报错:Error: The specified module could not be found.
前端
cxxcode39 分钟前
前端模块化发展
前端
不务正业的前端学徒43 分钟前
docker+nginx部署
前端
不务正业的前端学徒1 小时前
webpack/vite配置
前端
hhcccchh1 小时前
学习vue第八天 Vue3 模板语法和内置指令 - 简单入门
前端·vue.js·学习
yyf198905251 小时前
Vue 框架相关中文文献
前端·javascript·vue.js
粥里有勺糖1 小时前
开发一个美观的 VitePress 图片预览插件
前端·vue.js·vitepress
行者961 小时前
Flutter适配OpenHarmony:国际化i18n实现中的常见陷阱与解决方案
开发语言·javascript·flutter·harmonyos·鸿蒙
陟上青云2 小时前
一篇文章带你搞懂原型和原型链
前端