I'm using an application built with Angular 7. In src/assets, I have a sample excel file. To download an example excel file, I've built a download attachment technique. I can download it, but when I view the downloaded sample excel file, I receive an error. Excel cannot open the file "sample.xlsx" because the file format or file extension is invalid, according to the error message. Check to make sure the file is not corrupted and that the file extension corresponds to the file's format.
component.component.html
<button mat-raised-button (click)="downloadexcelfile()">
<button mat-raised-button (click)="download()">
component.component.ts
downloadexcelfile() {
if(navigator.msSaveBlob) {
// to support in IE 10+
let data: any;
this.HttpClient.get("./assets/sample.xlsx",{responseType: "blob"}).subscribe((res:any) => {
data = res;
// approach - 1
let csvData = new Blob([data], { type: 'text/csv;charset=utf-8;'});
// approach - 2
let csvData = new Blob([data], { type: 'application/vnd.ms-excel'});
// approach - 3
let csvData = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
navigator.msSaveBlob(csvData, "sample.xlsx");
})
}
else if(!navigator.msSaveBlob) {
let link = document.createElement("a");
link.href = "assets/sample.xlsx";
link.download = "sample.xlsx";
link.click();
window.URL.revokeObjectURL(link.href);
link.remove();
}
}
// approach - 4
download() {
if(navigator.msSaveBlob) {
// to support in IE 10+
let data: any;
this.HttpClient.get("./assets/sample.xlsx",{responseType: "arraybuffer"}).subscribe((res:any) => {
data = res;
// approach - 5
let csvData = new Blob([data], { type: 'text/csv'});
// approach - 6
let csvData = new Blob([data], { type: 'application/vnd.ms-excel'});
// approach - 7
let csvData = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
navigator.msSaveBlob(csvData, "sample.xlsx");
})
}
else if(!navigator.msSaveBlob) {
let link = document.createElement("a");
link.href = "assets/sample.xlsx";
link.download = "sample.xlsx";
link.click();
window.URL.revokeObjectURL(link.href);
link.remove();
}
}