vue excel file download

1. Encapsulate js files

This file is in the utils/index.js file and will be used later.

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

2. Package public download method

Some parameters can be passed in and the IE browser can make a judgment. When the IE browser downloads, the a tag cannot be used, so if no judgment is made, there will be no response.

import { param } from '@/utils'
import { getToken, getSid } from '@/utils/auth'

// 请求下载文件
export function blob(url, method = 'GET', data, fileName) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    if (method.toUpperCase() === 'GET') {
      url = `${url}?${param(data)}`
    }
    xhr.open(method, url, true)
    xhr.setRequestHeader('uiticket', getToken())
    xhr.setRequestHeader('sid', getSid() || '')
    xhr.setRequestHeader('Content-Type', 'application/json')
    xhr.responseType = 'blob'
    xhr.onload = function(data) {
      if (this.status === 200) {
      // 这里做一个IE浏览器的判断
        if (window.navigator && window.navigator.msSaveBlob) {
          var blobObject = new Blob([this.response]);
          window.navigator.msSaveBlob(blobObject, `${fileName}.xlsx`);
        } else {
          const blob = this.response
          const url = window.URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.href = url
          link.download = fileName
          link.style.display = 'none'
          document.body.appendChild(link)
          link.click()
          window.URL.revokeObjectURL(url)
          document.body.removeChild(link)
          resolve(url)
        }
      } else {
        reject('下载数据失败!')
      }
    }
    if (method.toUpperCase() === 'POST') {
      xhr.send(JSON.stringify(data))
    } else {
      xhr.send()
    }
  })
}

3. Use in the interface

import request from '@/utils/request'
import * as download from '@/utils/download'
// 导出模板
export function exportTemplate(data, fileName) {
  const url = (process.env.ENV === 'production' ? window.location.host + process.env.VUE_APP_BASE_API : process.env.VUE_APP_BASE_API) + 'xxxxxxxxURL'
  return download.blob(url, 'POST', data, fileName)
}

4. Use in vue project

That's probably it.

import { exportTemplate} from '../../api/permission/customCheck'
    handleUploadTemplate() {
      const obj = {}
      this.loading = true
      exportTemplate(obj, '测试' + new Date().getTime() + '.xlsx').then(response => {
        if (response) {
          this.msgSuccess('导出成功')
          this.loading = false
        } else {
          this.msgError(response.msg)
          this.loading = false
        }
      })
    },

Guess you like

Origin blog.csdn.net/weixin_45849417/article/details/131723741