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('导出失败!')
    })
  }
}
相关推荐
因_崔斯汀29 分钟前
用 AI 生成 Three.js 沉浸式网站,代码与 Skill 均已开源
前端·人工智能
葡萄城技术团队1 小时前
一键触发工作表中所有异步函数:用依赖单元格刷新 SpreadJS 公式
前端
Bigger1 小时前
谁动了我的 URL?——记一次微前端"灵异 Bug"的排查实录
前端·ai编程·vue-router
JavaGuide1 小时前
轻量开源版 IDEA 来了!
前端·后端
2601_962097481 小时前
JavaScript 异步编程
javascript·ajax·回调函数·异步编程·子线程
张洪权1 小时前
nest.js websocket 群聊----私聊功能
前端·nestjs
流光D1 小时前
AI Era: Building Web Sites and Configuring Nginx Reverse Proxy Process
前端·人工智能·nginx
sakidd1 小时前
VS Code 的 AI Chat 现在已经这么能干了?
前端
计算机魔术师2 小时前
英伟达砸130亿美元买下一个平台,黄仁勋到底在怕什么?
前端
全栈项目管理程序猿2 小时前
ArcGIS JS 基础教程(18):SceneLayer 场景图层
javascript