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('导出失败!')
    })
  }
}
相关推荐
萑澈2 小时前
Windows 7 运行 Electron 安装包报“不是有效的 Win32 应用程序”怎么办
javascript·windows·electron
W.A委员会2 小时前
JS原型链详解
开发语言·javascript·原型模式
懂懂tty3 小时前
React状态更新流程
前端·react.js
小码哥_常3 小时前
告别繁琐!手把手教你封装超实用Android原生Adapter基类
前端
她说彩礼65万3 小时前
C# 实现简单的日志打印
开发语言·javascript·c#
skywalk81633 小时前
pytest测试的时候这是什么意思?Migrating <class ‘kotti.resources.File‘>
前端·python
一只蝉nahc4 小时前
vue使用iframe内嵌unity模型,并且向模型传递信息,接受信息
前端·vue.js·unity
状元岐4 小时前
C#反射从入门到精通
java·javascript·算法
子兮曰4 小时前
Bun v1.3.12 深度解析:新特性、性能优化与实战指南
前端·typescript·bun
2401_885885045 小时前
易语言彩信接口怎么调用?E语言Post实现多媒体数据批量下发
前端