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

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...