How to download an Excel file with Angular 4 and HttpClient ?

15,903 views
Skip to first unread message

nicolas duminil

unread,
Sep 11, 2017, 8:43:39 AM9/11/17
to Angular and AngularJS discussion
Hello,

I need to call a JAX-RS service which returns an excel file and i need to download locally this file. I have googled to see how to do it in Angular and found lots of samples for Angular 2 which don't work in Angular 4 and HttpClient.

For example I found this:

public downloadFile2(bundleIds: Array<String>, langIds: Array<String>): Observable<Blob> {
let options = new RequestOptions({ responseType: ResponseContentType.Blob });
return this.http.get(this.url, options).map(res => res.blob());
}

 It doesn't compile and flags the following error message at the last line (options):

[ts]
Argument of type 'RequestOptions' is not assignable to parameter of type '{ headers?: HttpHeaders; observe?: "body"; params?: HttpParams; reportProgress?: boolean; respons...'.
Types of property 'headers' are incompatible.
Type 'Headers' is not assignable to type 'HttpHeaders'.
Property 'headers' is missing in type 'Headers'.

What seems to happen is that HttpClient requires HttpHeaders parameters while this example is using Headers. Could someone please provide me with a working example of downloading an Excel file or, at least, how to solve the error above ?

Many thanks in advance,

Nicolas

Sander Elias

unread,
Sep 11, 2017, 10:31:53 AM9/11/17
to Angular and AngularJS discussion
Hi Nicolas,

Have a look at the documentation on how to provide headers: https://angular.io/guide/http#headers
Right there is a sample on how to use custom headers.

Regards
Sander

testdeve...@gmail.com

unread,
May 10, 2018, 10:28:15 AM5/10/18
to Angular and AngularJS discussion
Hi Sander,
I am also facing a similar situation. I needed to download and save an excel file in Angular 5 using HttpClient. I viewed the Angular documentation and came up with the following code for my service call:-
DownloadExcelFile(): Observable<any> {
const httpOptions = {
headers: new HttpHeaders({ 'responseType': 'ResponseContentType.Blob',
'Content-Type': 'application/vnd.ms-excel'})};
return this.http.get(environment.baseurl + '/api/DownloadExcelFile', httpOptions);
} 

 and getting the data through the following Code:- 
this.dataService.DownloadQDMFile().subscribe(
(data) => {
if (data) {
const myBlob: Blob = new Blob([(<any>data)._body]);
saveAs(myBlob, 'SampleExcel.xlsx');
}
},
(err) => {
}
);

But I was always getting an error. I was able to download the file using Http request with the following Http service code:- 
DownloadExcelFile(): Observable<any> {
return this.http.get(environment.baseurl + '/api/DownloadExcelFile', { responseType: ResponseContentType.Blob});
});
}

Could you please explain why this isn't working and how to download using HttpClient.

Thanks in Advance.
Reply all
Reply to author
Forward
0 new messages