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('导出失败!')
    })
  }
}
相关推荐
@大迁世界1 天前
Firefox 本地模式:localhost 再见了 ?
前端·架构
米米商聊1 天前
同名附件为什么被 Map 覆盖?重复键与一对多索引
前端·javascript
echome8881 天前
Python 异常处理:try、else、finally 的正确搭配
开发语言·前端·python·异常处理·编程技巧
时间的情敌1 天前
OpenLayers 实战|Vue3 + OpenLayers 完整工程案例(加载天地图、要素、弹窗、绘制、WFS)
前端·openlayers
陈随易1 天前
下载神器!Motrix 停更三年后重写回归
前端·后端·程序员
前端的日常1 天前
一个人+AI做情侣食谱小程序,0 费用的服务器
前端·后端
计算机魔术师1 天前
谷歌搜索广告踩刹车,AI广告成为救命稻草
前端
总要学点什么1 天前
第81篇:数据可视化-PM2.5分布——让圆点的胖瘦替每座城市报出浓度
前端·信息可视化·echarts·cesium·空间分析
IT_陈寒1 天前
Vue的v-for里用了个临时变量,页面直接挂了
前端·人工智能·后端
hunter_0761 天前
一次 iOS 真机签名 409 的完整排查:证书、设备、描述文件为什么总是"对不上"
前端