代码之家  ›  专栏  ›  技术社区  ›  Dale Nguyen

如何将响应转换为Excel文件

  •  2
  • Dale Nguyen  · 技术社区  · 6 年前

    我向服务器发送了一个请求,然后得到了响应,但我不知道如何将此响应转换为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
    

    响应数据:

    à±; 根入口工作簿 Ba==h:#8X@“1校准1校准1校准1校准1校准1”$“#,##0#);(“$”###0)"$"#,##0_);红色 "$"#,##0.00_); ); (@ ) #.##0#,##0.000[$-1009]毫米日,yyyy@_($*

    ,##0.00_)

    ! # # `演示

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

    但是,当我打开文件时,它有错误,无法打开它。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Pandiyan Cool    6 年前

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

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

    Reference

    推荐文章