In daily development, we may encounter the situation of exporting Excel. The back end returns a file stream to us, and the front end needs to download the file stream as a URL address.

You can wrap this method as a utility class that can be called from elsewhere, which I put in utils.js

import axios from 'axios'
import Vue form 'vue'

/** * Export to Excel according to the back end return file flow *@param {Object} data* /
export function exportExcelMethod(data) {
  axios({
    method: data.method,
    url: `${data.url}${data.params ? '? ' + data.params : ' '}`.responseType: 'blob'.headers: {
      token: data.token
    },
    timeout: 8000.data: data.data
  })
    .then((res) = > {
      const link = document.createElement('a')
      const blob = new Blob([res.data], {
        type: 'application/vnd.ms-excel'
      })
      link.style.display = 'none'
      link.href = URL.createObjectURL(blob)

      // link. Download = res.headers['content-disposition'] // File name after download
      link.download = data.fileName // The file name to download
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      Vue.prototype.$message.success('Export successful! ')
    })
    .catch((error) = > {
      Vue.prototype.$message.error('Parameter error! ')})}Copy the code
<el-button type="primary" plain size="small" @click="exportLog"> </el-button>Copy the code
import { exportExcelMethod } from '@/utils'

exportLog() {
    const url = this.baseUrl
    const data = this.data
    const myObj = {
      method: 'post'.url: url,
      fileName: Log 'XXX'.token: this.token,
      data: { data }
    }
    exportExcelMethod(myObj)
  }
Copy the code