Export Data as Excel File in Angular | Angular Excel Export
Angular has always made itself standalone when it comes to implementing features, think of an idea & angular has it, speak of a functionality & angular provides the possibility to implement it. In regards to many other super powers that angular provide, In this article we learn how we can export any data to Excel file.
Yes! you heard it right, ANY DATA… sssshhhh 🤐…. do not hurry, if I say so, then we will do so. Don’t rush, always remember “Slow & Steady wins the race”. Now, 1… 2….3… Go 🏃
Step 1 : Creating a JSON file
To export any data as a excel file we first need “any data”, right ? So let us create a json file, for me it will be employees.json created in assets folder which will have an array of employee object with some fields, have a look below :
[
{
"userId": "rirani",
"jobTitleName": "Developer",
"firstName": "Romin",
"lastName": "Irani",
"preferredFullName": "Romin Irani",
"employeeCode": "E1",
"region": "CA",
"phoneNumber": "408-1234567",
"emailAddress": "romin.k.irani@gmail.com"
},
{
"userId": "nirani",
"jobTitleName": "Developer",
"firstName": "Neil",
"lastName": "Irani",
"preferredFullName": "Neil Irani",
"employeeCode": "E2",
"region": "CA",
"phoneNumber": "408-1111111",
"emailAddress": "neilrirani@gmail.com"
},
{
"userId": "thanks",
"jobTitleName": "Program Directory",
"firstName": "Tom",
"lastName": "Hanks",
"preferredFullName": "Tom Hanks",
"employeeCode": "E3",
"region": "CA",
"phoneNumber": "408-2222222",
"emailAddress": "tomhanks@gmail.com"
}
]
Step 2 : Fetching Data from JSON file
Now once we have a json file, it is time to fetch that data and store it in an array. Let us see how we can do that :
employees: any[] = [];
constructor(private http: HttpClient) {}
First we will inject httpClient module in constructor followed by creating an empty array named employees of any type. Do not forgot to import HttpClientModule in module.ts file.
Now once you have done the injections, create a function name as getJson() as shown below :
public getJSON(): Observable<any> {
return this.http.get('./assets/employees.json');
}
Please specify the correct path to your JSON file, as for me it was under assets folder. After this we will call this function in ngOnInit() and assign the values to employees array.
ngOnInit(): void {
this.getJSON().subscribe((data) => {
console.log(data);
this.employees = data;
});
}
Step 3 : Displaying Employees data to HTML page
Since we have the JSON data now, we need it to display it on our outlet. Although it is not necessary to display the data while exporting but from the user’s perspective it is always preferred to have a nice GUI. I have used tables to display the data and for styling I am using bootstrap.
So, I will just paste my HTML code, there is no hot-shot in it… 😉
<h2>Export Data as excel file in Angular</h2>
<hr />
<div class="d-flex">
<h4>Employees Data :</h4>
</div>
<hr />
<table class="table table-striped">
<thead>
<tr>
<th scope="col">SN.</th>
<th scope="col">UserId</th>
<th scope="col">JT</th>
<th scope="col">FN</th>
<th scope="col">LN</th>
<th scope="col">Name</th>
<th scope="col">Code</th>
<th scope="col">Region</th>
<th scope="col">No.</th>
<th scope="col">Email</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let employee of employees; let i = index">
<th scope="row">{{ i + 1 }}</th>
<td>{{ employee.userId }}</td>
<td>{{ employee.jobTitleName }}</td>
<td>{{ employee.firstName }}</td>
<td>{{ employee.lastName }}</td>
<td>{{ employee.preferredFullName }}</td>
<td>{{ employee.employeeCode }}</td>
<td>{{ employee.region }}</td>
<td>{{ employee.phoneNumber }}</td>
<td>{{ employee.emailAddress }}</td>
</tr>
</tbody>
</table>
Step 4: Creating an Export button
I will just the paste the code below, don’t think I had to give any explanations for that. I know my readers 🤗. Just remember that I am using bootstarp.
<div class="d-flex">
<h4>Employees Data :</h4>
<button class="btn btn-success p-1 mx-5" (click)="exportAsXLSX()">
Export
</button>
</div>
Step 5: Creating Excel Service
I know I know… the time has come now and therefore I will ask you not to jump into the code directly. Listen!!! 🙇 To reach a destination we need 2 things i.e. a vehicle & fuel which is referring to libraries as “file-saver” & “xlsx”. These libraries comes under @types/ module which can be installed with the below steps:
npm install @types/node --save
npm install @types/file-saver --save
npm install xlsx --save
Once you have done executing the above command you can import them in your service file as :
import * as FileSaver from 'file-saver';import * as XLSX from 'xlsx';
If we buy something we need a carry bag for it, right ? Also we can’t buy crude oil in paper bag, referring to which I mean that if we need to export data we need to specify the “type” of file & the “extension” of file. So let’s go ahead and do that :
const EXCEL_TYPE = 'application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet;charset=UTF-8';const EXCEL_EXTENSION = '.xlsx';
And now, since we have all the equipment’s ready & clean, let’s dig down the data, We will now create 2 functions naming “saveAsExcelFile()” & “exportAsExcelFile()”, their name itself specify their use.
saveAsExcelFile() :
private saveAsExcelFile(buffer: any, fileName: string): void {
const data: Blob = new Blob([buffer], {
type: EXCEL_TYPE,
});
FileSaver.saveAs(
data,
fileName + '_export_' + this.todaysDate + EXCEL_EXTENSION
);
}
The only thing which will revolve you mind from the above function is BLOB… Let me tell you that Blob is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data. For more information please refer : https://developer.mozilla.org/en-US/docs/Web/API/Blob
exportAsExcelFile() :
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'],
};
const excelBuffer: any = XLSX.write(workbook, {
bookType: 'xlsx',
type: 'array',
});
this.saveAsExcelFile(excelBuffer, excelFileName);
}
This function accepts 2 parameters, array of type any & a fileName… Firstly the array of raw data is converted in to an WoorkSheet and then that sheet is combined into a WorkBook. Once these steps are done, a constant buffer is created which will be further sent to our saveAsExcelFile() function for saving the file.
Yeah my friend, that’s it. Just 5 easy steps to export ….
Conclusion & Project Configuration Link
In this article we came across one more secret | super power possessed by angular of exporting data as an excel file. There are few allegations of using @types/node but if you are getting a result, then just let it go. There are multiple more ways to do so, but if you ask me ..? no other ways are fuel efficient to your vehicle.
Below I am providing you links of a demo configured project
https://stackblitz.com/edit/angular-ivy-k7wrcn
https://github.com/thesiddharthraghuvanshi/environment-variables-configuration-in-angular
Hope this article will help at some extent, please follow for more such articles.
Thankyou for your time & Happy Coding 😋