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('导出失败!')
    })
  }
}
相关推荐
电子IT笔记8 小时前
对接群晖NAS,上传和删除踩坑记录
前端·后端
计算机魔术师8 小时前
半年前说不缺钱,半年后150亿美元超募
前端
用户5708462574408 小时前
自动化发布器里最贵的 Bug:返回成功,但什么都没发生
前端
爱吃馒头不吃辣8 小时前
加一道题,改一天代码:题库即数据的降维打击
前端·架构
aiks_yuan8 小时前
Requestly规则使用技巧:前端联调、接口Mock与网络请求调试实战
前端
程序员老赵8 小时前
Docker 部署 MaxKB:轻松搭建企业级智能体平台
前端·docker·agent
码林鼠8 小时前
flutter状态管理入门教程-Riverpod
开发语言·javascript·flutter
踩蚂蚁9 小时前
输入关键词到离线模型:从 Wake Word 到多关键词 KWS 的一条工程链路
前端
互影派9 小时前
分享:Cocos 互动影游一套代码双端分发(Web H5 + Windows/Steam)实践
javascript