Javascript 从服务器下载 Excel 文件并保存在客户端

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29853359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:07:58  来源:igfitidea点击:

Download Excel file from server and save on client

javascriptexcelblobfilereader

提问by Gaui

I have a JavaScript app and an API that creates a Excel file and returns a byte array with the following headers:

我有一个 JavaScript 应用程序和一个 API,它创建一个 Excel 文件并返回一个带有以下标题的字节数组:

Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Content-Disposition:attachment; filename=List.xlsx

When I go the Excel resource API URL I'm prompted to download the Excel file. If I do so, it downloads fine and opens in Excel. All is good.

当我访问 Excel 资源 API URL 时,系统会提示我下载 Excel 文件。如果我这样做,它可以正常下载并在 Excel 中打开。一切都很好。

Now to the problem:

现在问题来了:

What I don't want is to expose the API URL in the user's browser window, so my goal is to:

我不想在用户的浏览器窗口中公开 API URL,所以我的目标是:

  • Download the Excel file via AJAX XMLHttpRequest
  • Store the contents (byte array) in a Blob
  • Create a data URI with the Blob
  • Open the data URI in a popup, that prompts the user to download the Excel file
  • 通过 AJAX XMLHttpRequest 下载 Excel 文件
  • 将内容(字节数组)存储在 Blob 中
  • 使用 Blob 创建数据 URI
  • 在弹出窗口中打开数据 URI,提示用户下载 Excel 文件

What I have is this:

我有的是这个:

It downloads the file, but when I try to open the file, Excel doesn't recognize it as a valid Excel file.

它会下载文件,但是当我尝试打开文件时,Excel 无法将其识别为有效的 Excel 文件。

// "data" is the contents from the server

var reader = new FileReader();
var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
reader.readAsDataURL(blob);

reader.onloadend = function (e) {
    window.open(reader.result, 'Excel', 'width=20,height=10,toolbar=0,menubar=0,scrollbars=no', '_blank');
}

回答by Gaui

I got it working. I just had to add the following to my XMLHttpRequest object:

我让它工作了。我只需要将以下内容添加到我的 XMLHttpRequest 对象中:

responseType: 'arraybuffer'

But it doesn't work in IE, because IE cannot open data URIs. Not even IE11.

但它在 IE 中不起作用,因为 IE 无法打开数据 URI。甚至没有IE11。

Anyway I found a great library called FileSaver.jswhich handles saving files for all major browsers (including IE10+)

无论如何,我找到了一个名为 FileSaver.js 的很棒的库,它可以处理所有主要浏览器(包括 IE10+)的文件保存