【问题标题】:How download Excel file in Vue.js application correctly?如何在 Vue.js 应用程序中正确下载 Excel 文件?
【发布时间】:2019-09-20 08:00:33
【问题描述】:

我正在努力在我的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()
});

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

我们发现.xlsx 的某些内容存在问题。您希望我们尽可能多地尝试和恢复吗?

【问题讨论】:

  • 感谢您提出这个问题。我被困在这里几个小时

标签: javascript excel vue.js blob xlsx


【解决方案1】:

您需要在 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);
});

【讨论】:

  • 非常感谢! :) 我使用您在帖子中描述的第一个选项,它对我有用。我可以再问你一个问题吗?!在下载过程中,是否可以更改 excel 文件中的样式?例如,我希望标题以不同的颜色突出显示。你的意见有可能吗?
  • 我不认为您是否可以即时进行任何修改,但您可以在下载之前在服务器端(在您的情况下为 NodeJS)操作您的文件。
  • 关于如何为此编写单元测试的任何建议?
  • @Tom 我不确定单元测试的问题出在哪里?如果您的测试总是返回相同的文件,您可以使用像 MD5 这样的哈希算法(快速但由于冲突而较弱)对其进行哈希处理,并在测试中验证返回的文件是否具有相同的哈希摘要
【解决方案2】:

我的案例成功了:

  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()
  })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-28
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    相关资源
    最近更新 更多