React 实现Excel 文件下载(实现导入导出)

封装的工具类,有页面需要使用此功能时可直接调用:

import apiPath from 'Common/apiPath'
import { message } from 'antd'

const Utils = {
  showErrorMsg: msg => { // 显示错误消息
    message.destroy()
    message.error(msg)
  },
  showSuccessMsg: msg => { // 显示成功消息
    message.destroy()
    message.success(msg)
  },
  showWarnMsg: msg => { // 显示警告消息
    message.destroy()
    message.warn(msg)
  },
 
  // 文件下载
   /** 
   *params 后台接口请求参数
   *url 后台接口地址
   *name 导出文件名称 
   * */ 
  downLoad: async (params = {}, url, name) => {
    console.log('文件下载', params)
    try {
      fetch(url, {
        method: 'POST',
        body: window.JSON.stringify(params),
        credentials: 'include',
        headers: new Headers({
          'Content-Type': 'application/json'
        })
      }).then(response => {
        console.log(response)
        response.blob().then(blob => {
          console.log(window.URL.createObjectURL(blob))
          //  let blobUrl = window.URL.createObjectURL(blob)
          const url = window.URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.href = url
          const fileName = `${name}.xlsx`//想要导出什么文件将.xlsx 改为文件后缀即可
          a.download = decodeURIComponent(fileName)
          a.click()
        })
      }).catch(error => {
        console.log(error)
      })
    } catch (e) {
      console.error('---文件下载异常----', e)
      Utils.showErrorMsg('文件下载失败,请联系管理员!')
    }
  },
}
export default Utils

调用工具类使用方法(以下载模板为例):

   // 下载模板
    xzmb =() => {
      const downloadUrl = //后台url路径
      const name = '学生数据导入模板'
      Utils.downLoad({
        templateName: '学生数据导入模板' //这是我后台接口需要的参数 通过名称找到文件 并下载
      }, downloadUrl, name)
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值