如何将响应转换为Excel文件

3

我向服务器发送了一个请求,然后得到了响应,但我不确定如何将此响应转换为Excel文件。

响应头:

Connection →keep-alive
cache-control →no-cache, no-store, max-age=0, must-revalidate
content-disposition →attachment; filename=demo.xls
content-length →7680
content-type →application/vnd.ms-excel
date →Wed, 19 Sep 2018 14:40:47 GMT
expires →0
pragma →no-cache
server →Apache
x-content-type-options →nosniff
x-frame-options →DENY
x-xss-protection →1; mode=block

响应数据:

这里展示的是一些编码混杂的文本,包括了一些关于工作簿及其单元格格式的信息。

这部分显示一些数字,但它们缺少上下文信息,难以理解。

这里还有一些特殊字符和乱码,可能与一个Demo相关。

我的尝试:

var blob = new Blob([result.data], 
      {
        'type': 'application/vnd.ms-excel',
      }    
)
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'demo.xls';
document.body.appendChild(link);

link.click();

然而,当我打开这个文件时,出现了错误,无法打开它。

需要帮助吗?谢谢。


你是否考虑过使用像 https://github.com/deblanco/xlsExport 这样的库来处理这个问题? - akseli
谢谢@askseli,我会查看的。 - Dale Nguyen
1个回答

1

将服务器响应下载为数组缓冲区。使用服务器的内容类型(应为application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)将其存储为Blob:

var httpPromise = this.$http.post(server, postData, { responseType: 'arraybuffer' });
httpPromise.then(response => this.save(new Blob([response.data],
    { type: response.headers('Content-Type') }), fileName));

将 Blob 保存到用户设备:
save(blob, fileName) {
    if (window.navigator.msSaveOrOpenBlob) { // For IE:
        navigator.msSaveBlob(blob, fileName);
    } else { // For other browsers:
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(link.href);
    }
}

参考文献


1
太棒了,你救了我的命。响应应该是一个数组缓冲区! - Dale Nguyen
酷,玩得开心 :) - Pandiyan Cool

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接