How To Export Data To Excel File in Angular 2
Today I want to explain how to export your data to an excel file in Angular. You can do it in two ways. First, fetch the json data in Angular and then convert the data to an excel file. Or you can send the data in an excel file directly from your server side. I will show you both of them.
Let’s make it firstly by creating the excel file on client. So, we must fetch the json data from server side. This is the code to fetch the json data in html.
1 2 3 |
<div class="col-md-2" > <button class="btn btn-success btn-block" id="btnExcel" (click)="excel()"><span class="glyphicon glyphicon-th"></span> Excele Aktar (Client)</button> </div> |
And the component code.
1 2 3 4 5 6 7 8 |
excel(){ this.div_visible = true;// progres start. this.service.ExcelExport(this.selectedUserCode,this.selectedCity) .subscribe(data => this.downloadFile(data)), error => this.messageService.add({severity: 'error', summary: 'Error message', detail: 'Error while downloading excel file.'}); () => console.log('File download finished.'); } |
And we will convert data to excel file in downloadFile method.
1 2 3 4 5 |
downloadFile(data:Data): void { this.service.exportAsExcelFile(data,'CrashReport'); this.messageService.add({severity: 'info', summary: 'Info Message', detail: 'Excel File has been downloaded.'}); } |
This is the code we use in the service. We must get Sheetjs package before using it. Import it with this command.
1 |
$ npm install xlsx |
And then this code will be in your service.
1 2 3 4 5 6 7 8 |
import * as XLSX from 'xlsx'; public exportAsExcelFile(json: any[], excelFileName: string): void { const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json); const workbook: XLSX.WorkBook = {Sheets: {'data': worksheet}, SheetNames: ['data'] }; XLSX.writeFile(workbook, this.toExportFileName(excelFileName,"xlsx")); }see |
That’s all. I will explain downloading excel file from server in my next post
If you have question do not forget to write from the chat button next to it or from the comment
Can you inform me what platform are you utilizing on this website?
Hello Michel, I am using wordpress for my web site.