vue项目实现导出数据到excel

实现导出功能分两种,一种是客户端拿到数据做导出,第二种是服务器端处理好,返回一个数据流实现导出

第一种网上很容易找到,也很好用,本文要说的是第二种。

fetchExport({
        id: this.sourceId,
        begin: this.$route.query.begin,
        end: this.$route.query.end
      }).then(res => {
        const blob = new Blob([res.data], {
          type: 'application/vnd.ms-excel',
          crossOrigin: 'Anonymous'
        })
        const objectUrl = URL.createObjectURL(blob)
        window.location.href = objectUrl
      }).catch(err => {
        console.log(err)
      })

  

服务器端返回的是流数据,js提供了对应的处理方法,fetchExport是封装的ajax请求方法,利用axios创建一个实例,请求头要特别注意设置响应类型,否则下载的表格异常,如下

export function fetchExport(query) {
  return request({
    url: '你的url',
    method: 'get',
    params: query,
    responseType: 'arraybuffer', // 这个一定要有
    xsrfHeaderName: 'Authorization'
  })
}

  

原文地址:https://www.cnblogs.com/diantao/p/10960353.html