项目中导出文档数据

在后台管理系统中,存在大量的数据表格,有时需要以任意格式导出,这里封装了一个post与get的导出文档函数!!!

1、GET

/**
 * 页面【导出】表格 - 【GET】
 * @param name 导出页面的名称
 * @param host 导出的地址 `/api/center/data/workerRanking/export?id=${id}`
 * @returns {HTMLDivElement}
 */
export const downloadExportGet = (name,host) => {
  fetch(host, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/get'
    }
  })
    .then(response => response.blob())
    .then(blob => {
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${name}-数据导出[${dateFormat()}].xlsx`;  // 下载的文件名
      a.click();
      window.URL.revokeObjectURL(url);
    });
}

/**
 * 打开新页面【GET】
 */
window.open(`/api/center/data/workerRanking/export?id=${id}`)

2、POST

/**
 * 页面【导出】表格 - 【POST】
 * @param name 导出页面的名称
 * @param host 导出的地址 `/api/center/data/workerRanking/export`
 * @param data 请求的数据
 * @returns {HTMLDivElement}
 */
export const downloadExportPost = (name,host,data) => {
  fetch(host, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    },
    body: JSON.stringify(data)
  })
    .then(response => response.blob())
    .then(blob => {
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${name}-数据导出[${dateFormat()}].xlsx`;  // 下载的文件名
      a.click();
      window.URL.revokeObjectURL(url);
    });
}

3、兼容POST与GET

/**
 * 页面【导出】表格
 * @param name 导出页面的名称
 * @param host 导出的地址  `/api/center/data/workerRanking/export`
 * @param data 请求的数据(仅适用于POST请求)
 * @param isGet 是否为GET请求(默认false)
 * @returns {Promise<HTMLDivElement>}
 */
export const downloadExport = (name, host, data = null, isGet = false) => {
  const headers = {};

  if (isGet) {
    headers['Content-Type'] = 'application/get';
  } else {
    headers['Content-Type'] = 'application/json;charset=UTF-8';
  }

  return fetch(host, {
    method: isGet ? 'GET' : 'POST',
    headers,
    body: data ? JSON.stringify(data) : null,
  })
    .then(response => response.blob())
    .then(blob => {
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${name}-数据导出[${dateFormat()}].xlsx`;  // 下载的文件名
      a.click();
      window.URL.revokeObjectURL(url);
    });
};

  • 11
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值