In this article, We will learn how we can upload an Excel file and then read its data using Angular.
To read the data from the Excel file, we will use an NPM library called XLSX
. This will help us read the data from the excel file as well as convert it to JSON so that we can later use it as a payload to APIs.
Let’s implement it step by step:
Step 1 – Install the XLSX Package
The first thing you need is, install the xlsx
package from npm into your Angular project using the npm install
command.
npm install xlsx --save
If the xlsx
package is installed successfully, it will be added to the dependencies section of the package.json file. This is because of the --save
option we provided while installing it.
Step 2 – Add File Input in the Template File
Next, We need to add an <input type="file">
element in our template file. It will allow us to select an excel file from our PC.
<div style="margin: 50px auto;width: 50%;"> <h2>Please select a file: </h2> <input type="file" (input)="onFileChange($event)" multiple="false"> </div>
Step 3 – Read Excel File Data
In the previous step, we bound a function onFileChange()
to the (input)
event. Now, we need to define this function in our .ts file. This function will be invoked whenever you upload a file.
Add the below code inside the .ts file:
import { Component, OnInit } from '@angular/core'; import * as XLSX from "xlsx"; onFileChange(evt: any) { const target: DataTransfer = <DataTransfer>(evt.target); if (target.files.length > 1) { alert('Multiple files are not allowed'); return; } else { const reader: FileReader = new FileReader(); reader.onload = (e: any) => { const bstr: string = e.target.result; const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' }); const wsname = wb.SheetNames[0]; const ws: XLSX.WorkSheet = wb.Sheets[wsname]; let data = (XLSX.utils.sheet_to_json(ws, { header: 1 })); // Print the Excel Data console.log(data); } reader.readAsBinaryString(target.files[0]); } }
Sample Output:
If you try to upload an excel file, it will print the excel data in the below format:
[ ["Id", "First Name", "Last Name", "Age"], [1, "John", "Doe", 24], [2, "James", "Bond", 21], [3, "Will", "Smith", 25], [4, "John", "Doe", 23] ]