如何在 Vue.js 应用程序中正确下载 Excel 文件?

How download Excel file in Vue.js application correctly?

我很难在我的 Vue.js 应用程序中下载 xlsx 格式的 Excel 文件。我的 Vue.js 应用程序向 Node.js 应用程序发出 post 请求,后者从远程 SFTP 服务器下载 Excel 文件。后端应用程序工作没有任何问题。

在 Vue.js 应用程序中,我使用下一个代码:

axios.post(config.backendHost + '/excel', {
  file_name: fileName
}).then((response) => {
  const url = URL.createObjectURL(new Blob([response.data], {
    type: 'application/vnd.ms-excel'
  }))
  const link = document.createElement('a')
  link.href = url
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
});

通过浏览器下载文件后,文件自动打开,我遇到如下错误:

We found a problem with some content .xlsx. Do you want us to try and recover as much as we can?

您需要在 post 调用中添加响应类型作为第三个参数

{
    responseType: 'blob'
}

你的最终代码就是这样

axios.post(config.backendHost + '/excel', {
    file_name: fileName
}, {
    responseType: 'blob'
}).then((response) => {
    const url = URL.createObjectURL(new Blob([response.data], {
        type: 'application/vnd.ms-excel'
    }))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
});

或者您可以使用库 FileSaver.js 来保存您的文件

import FileSaver from 'file-saver'

axios.post(config.backendHost + '/excel', {
    file_name: fileName
}, {
    responseType: 'blob'
}).then((response) => {

    // response.data is a blob type
    FileSaver.saveAs(response.data, fileName);
});

我的案例成功了:

  axios.get(`/api/v1/companies/${companyId}/export`, {
    responseType: 'blob',
  }).then((response) => {
    const url = URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute(
      'download',
      `${companyId}-${new Date().toLocaleDateString()}.xlsx`
    )
    document.body.appendChild(link)
    link.click()
  })