通過get或post請求下載excel表格的解決辦法

get請求方式

var downURL = '下載接口'  

var getData = '?starTime=20180922&endTime=20180925'

var request = downURL+getData

window.open(request)

或者是用a標籤,herf屬性指向下載的地址。比較簡單。直接下載。

post請求方式。

第一步:讓後端將下載的接口的response header設置:

Content-disposition: attachment; filename=數據報表.xlsx(表示會直接下載文件,文件名爲‘數據報表’)

Content-Type:application/octet-stream (二進制流數據,如常見的文件下載)

第二步:修改axios請求的responseTypearraybuffer,以post請求爲例:

 axios({
      method: 'post',
       url: '/api/main/manage/memberLogAttendance/findPage',
         responseType: 'arraybuffer',
         data: para,
        headers: {
          token: this.token
         }
      }).then(res => {
      console.log('111')
      this.download(res.data) // 注意,這裏一定是res.data,不然導出的excel會亂碼
     console.log(err)
     })

download(data) {
      if (!data) {
        return
      }
      const url = window.URL.createObjectURL(new Blob([data]))
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', '考勤統計.xlsx')
      document.body.appendChild(link)
      link.click()
      URL.revokeObjectURL(link.href) // 釋放URL 對象
      document.body.removeChild(link)
      link = null
    },

遇到的問題解決辦法
1、 下載的excel亂碼問題,res返回的數據,需要取res.data再去new Blob,亂碼原因就是這個。

2、我的axios請求,使用了全局的攔截器,本來是通過res.success來判斷接口有沒有請求成功,但是,這裏就需要對流數據接口進行排除,流並沒有返回這個res.success,不再是json數據格式,所以可以通過響應頭的content-type來進行判斷排除,這也就可以繼續使用統一的攔截器。

service.interceptors.response.use(
  // response => response,// 如果需要返回http信息譬如頭部信息或狀態,就使用該方式
  response => {
    const res = response.data
    // 如果是請求的流數據,直接返回res去處理,res.success爲undifiend
    if (response.headers['content-type'] === 'application/octet-stream') {
      return res
    }
    // 如果返回後端定義的code不是 1 ,就視爲一個錯誤返回.
    if (res.success !== 1) {
      Message({
        message: res.errMsg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      if (res.errCode === 'err.token.outtime') { // token超時
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      }
      return Promise.reject(res || 'Error')
    } else {
      return res
    }
  },

參考地址:
https://my.oschina.net/u/3964830/blog/2222103

https://www.cnblogs.com/HappyYawen/p/8623852.html

https://blog.csdn.net/Shimeng_1989/article/details/81773868

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章