George87
George87

Reputation: 92

Get excel document with Angular and save to disk

I need to get an excel file (xlsx) from the server through Angulars $http or something else.

The problem is that the file behind a REST like service which requires custom headers to perform authentication.

If the file was not behind Auth custom headers i could have used window.open() which was tested and worked fine, but the file is supposed to be secured so it was moved behind Auth service.

I can use angular to get the response from the server and write it to file as blob but the content is unreadable.

Does anyone have an idea how to achieve this?

Upvotes: 0

Views: 982

Answers (2)

anty
anty

Reputation: 713

For anyone interested:

Building on George87's answer, I was able to find a solution based on the angular $http service rather than the XMLHttpRequest API. The advantage of $http is that it supports promises.

The below TypeScript code should work. Just make sure to inject the $http service, as well as the fileSaverService into your angular Controller. The config parameter can be used to set, for instance, an 'Authorization' header for the request.

private downloadExcelFile = (url: string, fileName: string) => {
    const config: angular.IRequestShortcutConfig = {
        headers: {
            Authorization: auth,
        },
        responseType: 'blob',
    };
    this.$http.get(`${url}?name=${fileName}`, config)
        .then((response) => {
            this.fileSaverService.saveAs(response.data, '<localFileName>.xlsx');
        });
}

Upvotes: 1

George87
George87

Reputation: 92

I have found the answer to my question, i used XMLHttpRequest.

Sample code for others:

var xhr = new XMLHttpRequest();
xhr.open("GET", "test.xlsx");
xhr.responseType = "blob";

xhr.onload = function () {
    if (this.status === 200) {
    xhr.response.type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    saveAs(xhr.response, "test.xlsx")
    }
};
xhr.send();

Save as is a method from here: https://github.com/eligrey/FileSaver.js

Upvotes: 0

Related Questions