Intro
React, is one of the most popular frontend framework. Thanks to the great community we can easily read and process data directly from an xls file.
In this guide i will walk you through the steps on how to read data from a spreadsheet and display it on your react application.
Prerequisites
Before you begin make sure you have,
Node and npm installed on your system.
Step 1
Install Sheet JS.
npm install xlsx
Step 2
Import Sheet js into your jsx file.
import * as XLSX from 'xlsx';
Step 3
Create a function to handle upload of the xls file.
Start by creating a reader variable using a file reader constructor.
const reader = new FileReader();
Utilize the readAsBinaryString method to initiate the reading process for the specified file from the event argument.
reader.readAsBinaryString(e.target.files[0]);
Once the file has been successfully read, the load event is triggered. Proceed to extract the data following the steps and assign it to a variable.
reader.onload = (e: any) => { const data = e.target.result; const workbook = XLSX.read(data, { type: 'binary' }); const firstSheet = workbook.SheetNames[0]; const secondSheet = workbook.SheetNames[1]; const firstSheetData = XLSX.utils.sheet_to_json(workbook.Sheets[firstSheet]); const secondSheetData = XLSX.utils.sheet_to_json(workbook.Sheets[secondSheet]); console.log({first_sheet: firstSheetData, second_sheet: secondSheetData}) };
After following these steps, you should have a function similar to this.
const handleFileUpload = (e)=> { const reader = new FileReader(); reader.readAsBinaryString(e.target.files[0]); reader.onload = (e: any) => { const data = e.target.result; const workbook = XLSX.read(data, { type: 'binary' }); const firstSheet = workbook.SheetNames[0]; const secondSheet = workbook.SheetNames[1]; const firstSheetData = XLSX.utils.sheet_to_json(workbook.Sheets[firstSheet]); const secondSheetData = XLSX.utils.sheet_to_json(workbook.Sheets[secondSheet]); console.log({first_sheet: firstSheetData, second_sheet: secondSheetData}) };
Leave a like if this helped, Thanks
Happy Coding!
Top comments (1)
great tutorial