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('导出失败!')
    })
  }
}
相关推荐
自然 醒4 分钟前
前端如何实现在线预览office常见文件功能?
前端·vue.js
肉肉不吃 肉37 分钟前
前端调试跨域如何解决
前端·vue.js
Liora_Yvonne41 分钟前
为什么你写了3年前端还是搭不好一个项目
前端·架构
snow@li43 分钟前
Java:后端项目会有一个类似前端node_modules的目录吗 / jar包在本地仓库 ~/.m2/repository 中按版本共存
java·开发语言·前端
weedsfly44 分钟前
单例模式在前端中的正确打开方式
前端·javascript·面试
PedroQue991 小时前
uni-router新推useUniEventChannel,彻底解决页面通信难题
前端·uni-app
IT_陈寒1 小时前
Vite冷启动快?我遇到了个奇怪的依赖问题
前端·人工智能·后端
2603_955279701 小时前
通过 brew upgrade cmake 升级到最新版本
前端
FREEDOM_X1 小时前
Linux 进程间通讯(IPC)——总结
linux·c语言·前端·嵌入式硬件·struts
WWBQU1 小时前
前端day06
前端