Skip to main content

Export Data to Excel in Angular Using ExcelJS

 

When we develop a simple application or complex enterprise application using any technology, The end-user always needs the report data in an Excel file. Why because most people rely on excel file. I worked with various Angular Enterprise applications. In all applications, the customer asked us to give a downloadable excel file using various filters.

In this tutorial, you will learn, how to download an excel file using Angular. I am going to show a demo of excel file download using ExcelJS and File Saver plugin. If you are an Angular developer and looking for export data to excel, then this post will help you more. We will see them one by one.

Step 1. Create New Angular Project

Create a new Angular project using the below command.

ng new angular-excel-example

Once the initial setup is done, then open the project folder using the VS code editor.

Step 2. Install ExcelJS Plugin

ExcelJS plugin is used to read and write excel file. It is rich in functionality. You can style rows and columns. Even you can add images to excel files. That’s why many people using this library.

Install ExcelJS using the below command.

npm install exceljs --save

Step 3. Install File Saver

FileSaver.js is the solution to saving files on the client-side and is perfect for web apps that generate files on the client.

Install file saver plugin using the below command.

npm install file-saver --save

Step 4. Create Button With Click Event

Create a button on the app.component.html file with click event.


<div>

    <button class="centre btn mc" (click)="downloadExcel()">Download</button>

</div>

Step 5. Import ExcelJS and File Saver Plugin

Open the app.component.ts file and import the ExcelJS and File Saver plugin using the below code.


import { Workbook } from 'exceljs'; import * as fs from 'file-saver';

Step 6. Create a Downloadable Excel File

Here I am going to explain, each piece of code in a step by step manner.

  1. First, we need data in the JSON format. You can create dummy data like me for testing purposes or you can get the data from the server.

Here I creating a variable with some name and age data.

json_data=[{
		"name": "Raja",
		"age": 20
	},
	{
		"name": "Mano",
		"age": 40
	},
	{
		"name": "Tom",
		"age": 40
	},
	{
		"name": "Devi",
		"age": 40
	},
	{
		"name": "Mango",
		"age": 40
	}
]

2. Next, create a workbook excel workbook using

  //create new excel work book
let workbook = new Workbook();

3. From the workbook, we can create a new sheet using the addWorksheet() function. Give a sheet name here

//add name to sheet
let worksheet = workbook.addWorksheet("Employee Data");

4. Add column header using the addRow() function. In the JSON data, I have only two columns. That’s why I creating the only two columns.

//add column name
let header=["Name","Age"]
let headerRow = worksheet.addRow(header);

5. Now add the JSON data to the worksheet using the for loop.

for (let x1 of this.json_data)
{
  let x2=Object.keys(x1);
  let temp=[]
  for(let y of x2)
  {
    temp.push(x1[y])
  }
  worksheet.addRow(temp)
}
6. Set the file name and call the write function to create a downloadable excel file.


//set downloadable file name
let fname="Emp Data Sep 2020"

//add data and file name and download
workbook.xlsx.writeBuffer().then((data) => {
  let blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
  fs.saveAs(blob, fname+'-'+new Date().valueOf()+'.xlsx');
});












































































Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

JavaScript new features in ES2019(ES10)

The 2019 edition of the ECMAScript specification has many new features. Among them, I will summarize the ones that seem most useful to me. First, you can run these examples in  node.js ≥12 . To Install Node.js 12 on Ubuntu-Debian-Mint you can do the following: $sudo apt update $sudo apt -y upgrade $sudo apt update $sudo apt -y install curl dirmngr apt-transport-https lsb-release ca-certificates $curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash - $sudo apt -y install nodejs Or, in  Chrome Version ≥72,  you can try those features in the developer console(Alt +j). Array.prototype.flat && Array.prototype. flatMap The  flat()  method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. let array1 = ['a','b', [1, 2, 3]]; let array2 = array1.flat(); //['a', 'b', 1, 2, 3] We should also note that the method excludes gaps or empty elements in the array: let array1 ...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...