
Angular Download Excel File From Web API
To download an Excel file from a Web API using Angular, you can use Blob JS. Here are the steps to download the file:
1: Add a download button in yout template file
excel-file-download.component.html
<button type="button" (click)="downloadexcel()">Download Excel</button>
2: Create excel-file-download.component.ts to handle file uploads: Create a component that will allow users to download excel file. Here's an example of how the component may look like:
excel-file-download.component.ts
import { Component } from '@angular/core';
import { ExcelFileDownloadService } from './excel-file-Download.service';
@Component({
selector: 'app-excel-file-download',
templateUrl: './excel-file-download.component.html'
})
export class ExcelFileDownloadComponent {
constructor(private excelFileDownloadService: ExcelFileDownloadService) { }
downloadexcel() {
let fileName = 'filetodownload'
this.excelFileDownloadService.download(fileName).subscribe((response: any) => {
if ('application/json' === response.headers.get('Content-Type')) {
const reader = new FileReader();
reader.addEventListener('loadend', (e:any) => {
console.log(JSON.parse(e.srcElement['result']));
let errorResponse = JSON.parse(e.srcElement['result']);
console.log('Message - got json instead of file', errorResponse.message);
});
reader.readAsText(response.body);
} else {
console.log('File downloaded successfully.');
this.downloadFile(response.body);
}
}, (error) => {
console.error('Error uploading file:', error);
});
}
downloadFile(data: Response | any) {
const blob: Blob = data as Blob
let link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = `example.xlsx`;
link.click();
}
}
3: Create a File Download service: Create a excel file download service that will handle the file download functionality. This service should have a method that will make a POST request to the server to download the file. Here's an example of how the file download service may look like:
excel-file-Download.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable()
export class ExcelFileDownloadService {
constructor(private http: HttpClient) { }
download(fileName: string) {
return this.http.post('http://your-api-url.com/excel-file', fileName, { observe: 'response', responseType: 'blob'});
}
}