What is Angular?
Angular is a client side JavaScript Framework which allows us to create Reactive client-side applications.
It's a great approach for a Single Page Application.
By default it supports two-way data binding.
Why should we use Services in Angular?
Angular service methods can be invoked from any component of Angular, like Controllers, Directives, etc.
This helps in dividing the web application into small, different logical units which can be reused.
We use the @Injectable class decorators to automatically resolve and inject all the other classes. This only works if each parameter has a TypeScript type associated with it, which the DI framework uses as the token.
What is a dependency?
When module A in an application needs module B to run, then module B is a dependency of module A.
Dependency Injection is a way of architecting an application so code is easier to re-use, easier to test and easier to maintain.
Angular comes with a Dependency Injection (DI) framework of it’s own and it’s used throughout Angular code.
Implement Dependency Injection in Angular
Below are the ways to implement DI in Angular,
Using @Injectable() in the service
Using @NgModules() in the module
Using Providers in the component
Step 1
Create an Angular Project,
The command to create a new Angular project “ng new <myNewApp>”. Let's create an Angular project using the following commands.
Step 2 - Create a Service
Open the above created project in Visual Studio code and create service by using the following command “ng generate service <myService>”.
Step 3
Create a JSON file from any location Ex [assets/yourfilename.json]. Store the array values once JSON is created.
- {
- "Cardetails": [{
- "Id": 1,
- "CarName": "Hummer",
- "Model": "H3",
- "Mileage": "196321",
- "Color": "Pink"
- }, {
- "Id": 2,
- "CarName": "Chevrolet",
- "Model": "1500 Silverado",
- "Mileage": "195310",
- "Color": "Blue"
- }, {
- "Id": 3,
- "CarName": "Infiniti",
- "Model": "M",
- "Mileage": "194846",
- "Color": "Puce"
- },
- }
Step 4
Open the created service and add angular/http service by using the following command npm install @angular/http, using the follwing code.
- import {
- Http
- } from '@angular/http';
- export class {
- constructor(private http: Http) {}
Step 5
Get the stored JSON file through the service that you have created.
- Getdata() {
- return this.http.get("assets/Cardetails.json").map(res => {
- return res.json()
- });
- }
- }
Step 6
Add the below code in the file app.module.ts
- import {
- HttpModule
- } from '@angular/http'
- import {
- XlsServiceService
- }
- rom './xls-service.service'
- imports: [
- HttpModule
- ],
- providers: [
- XlsServiceService
- ],
Step 7
Add the following code to the file “app.component.ts”
- import {
- XlsServiceService
- } from './xls-service.service'
- constructor(private excelservice: XlsServiceService) {}
- ngOnInit() {
- this.Getdetails()
- }
- Getdetails() {
- this.excelservice.Getdata().subscribe(check => {
- this.listdetails = check.Cardetails
- });
- }
Step 8
Install file-saver and xlsx through the commands “npm install file-saver” and “npm install xlsx”
Now, open the ‘excel.service.ts' and paste the following code.
Step 9
Declare file type and file extesion with the below code.
- const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
- const EXCEL_EXTENSION = '.xlsx';
Step 10
Code to export JSON in excel file.
- public exportAsExcelFile(json: any[], excelFileName: string): void {
- const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
- console.log('worksheet', worksheet);
- const workbook: XLSX.WorkBook = {
- Sheets: {
- 'data': worksheet
- },
- SheetNames: ['data']
- };
- const excelBuffer: any = XLSX.write(workbook, {
- bookType: 'xlsx',
- type: 'array'
- });
- this.saveAsExcelFile(excelBuffer, excelFileName);
- }
- private saveAsExcelFile(buffer: any, fileName: string): void {
- const data: Blob = new Blob([buffer], {
- type: EXCEL_TYPE
- });
- FileSaver.saveAs(data, fileName + '_export_' + new Date().getHours() + ':' + new Date().getMinutes() + ':' + new Date().getSeconds() + EXCEL_EXTENSION);
- }
Step 11
Open the file “app.component.html” and paste the following code to see the HTML template
- <button(click)="Exportelx()">GenreateXls</button>
Step 12
In HTML page, add a button to call a click function to export an excel file which calls the method in service.
- Exportelx() {
- this.excelservice.exportAsExcelFile(this.listdetails, "Carinformation")
- }
To see the output in browser, use the following command “ng serve --open”
Summary
We learned how to export Excel files in Angular applications.