vue+element ui实现导出Excel文件

首先,一定一定要设置请求头:responseType: 'blob',

一开始试了一下直接调用的,就是像平常调用接口那样,发现返回来一堆乱码,所以,

const link = document.createElement('a')
link.download = fileName
link.href = objectUrl
link.click()
也是关键
其他位置像正常连接口那样写就可以了,我是这样写的,封装好的接口:
 <el-button type="primary" class="refresh" @click="onCheckedOut">导出</el-button>
import {exportData} from 'config/index'
 onCheckedOut () { // 导出
   exportData({
     url: '/admin/user/info/export'
   }).then(res => {
     if (res.status == 200) {
       let fileName = res.headers['content-disposition'].split('=')[1]
           let objectUrl = URL.createObjectURL(new Blob([res.data]))
           const link = document.createElement('a')
           link.download = fileName
           link.href = objectUrl
           link.click()
     } else {
          this.$message.error('出现异常请联系管理员!')
     }
   }).catch(err => {
     this.$message.error('出现异常稍后再试!')
   })
}

config/index.js

export const exportData = ({ url, data }) => { // 导出文件使用
  return httpDowload({ url, data, method: 'post' })
}
export const httpDowload = httpParams => {
  let { url, data, method } = { url: '', data: {}, method: 'get', ...httpParams }
  try {
    let params = {}
    if (method === 'get') {
      params = data
      data = {}
    }
    return axios({
      baseUrl: httpParams.baseURL || '/admin',
      url,
      method,
      params,
      data,
      headers: setHeaders(),
      responseType: 'blob'
    }).then((zData) => handleResponse(zData))
  } catch (err) {
    console.log(err)
  }
}
function handleResponse (data) {
  if (data.status !== 200) {
    return Promise.reject(data)
  } else {
    return Promise.resolve(data)
  }
}
export function setHeaders () {
  const token = sessionStorage.getItem('token') === null ? '' : sessionStorage.getItem('token')
  return {
    TOKEN: token
  }
}

 

posted @ 2020-03-12 10:27  圆圆呀~  阅读(8336)  评论(0编辑  收藏  举报