Front-end download EXCEL

Table of contents

1. Binary

1.1 The request interceptor handles it separately

1.2 Set the request header

1.3 convert excel

2. Download local excel


1. Binary

1.1 The request interceptor handles it separately

service.interceptors.response.use(
  response => {
    const res = response.data
    const requestType = response.config.method

    // 导出 excel
    if (response.config.headers.responseType === 'blob') {
      return response
    }

    if (res.code !== 200) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 3 * 1000
      })

      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      // return res
      if (requestType !== 'get') {
        Message({
          message: res.message,
          type: 'success',
          duration: 3 * 1000
        })
      }
      return response
    }
  },

1.2 Set the request header

// 下载导入歌曲模板excel
export function exportTemplate() {
  return request({
    url: '/song/export/template',
    method: 'get',
    responseType: 'blob',
    headers: {
      responseType: 'blob',
      accept: 'application/octet-stream'
    }
  })
}

1.3 convert excel

// 下载导入歌曲模板
    exportTemplate() {
      exportTemplate().then(data => {
        console.log('下载模板')
        console.log(data.data.data)
        const url = window.URL.createObjectURL(new Blob([data.data.data],
          {
            type: 'application/vnd.ms-excel'
          }
        ))
        console.log(url)
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', '歌曲模板.xlsx')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link) // 下载完成移除元素
        window.URL.revokeObjectURL(url) // 释放掉blob对象
      }).catch(err => {
        console.log('下载失败')
        console.log(err)
      })
    },

2. Download local excel

// 下载模板文件
    downloadExcel() {
      // console.log(process.env.BASE_URL)
      const linkA = document.createElement('a')
      // 路径中'/'为根目录,即index.html所在的目录
      linkA.href = './template.xlsx'
      // 下载下来的文件名
      linkA.download = '电竞模板文件'
      // 添加点击
      linkA.click()
    }

 

Guess you like

Origin blog.csdn.net/weixin_39763711/article/details/128375934