3

I send a request to a server, then got the response, but I am not sure how to turn this response to an Excel file.

Response header:

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

Response data:

��ࡱ�;�� �������������������������������������������������������������������RootEntry������������Workbook������������������������������������������������������������������������������������������������������������������������������������� ��A����\pmidadm B�a=���=h:�#8X@�"��1���Arial1���Arial1���Arial1���Arial1���Calibri1���Calibri1���Calibri"$"#,##0_);("$"#,##0)"$"#,##0_);Red "$"#,##0.00_);(* "-"??);(@) �#.##0� #,##0.000�[$-1009]mmmm d, yyyy;@�_($*

,##0.00_)��� � ��� �� ��� �� ��� �� ��� �� ��� �� ��� �� ��� �� ��� �� ��� �� ��� �� ��� �� ��� �� ��� �� ��� �� � �

�+�� �� �)�� �� �,�� �� �*�� �� � �� �� �!� � � � � �"� ��#� � � ��#� ��!� ��#� � #� ������������������`�Demo

Here is what I tried:

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

However, when I open the file, it has error, and cannot open it.

Any helps? Thanks,

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
Dale Nguyen
  • 1,930
  • 3
  • 24
  • 37

1 Answers1

1

Download the server response as an array buffer. Store it as a Blob using the content type from the server (which should be application/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));

Save the blob to the user's device:

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

Pandiyan Cool
  • 6,381
  • 8
  • 51
  • 87