How to read XLS Spreadsheets with React js.

how-to-read-xls-spreadsheets-with-react-js.

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,
1 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!

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
a-year-with-chatgpt-and-product-innovation:-navigating-the-ai-landscape

A year with ChatGPT and product innovation: Navigating the AI landscape

Next Post
how-to-deliver-a-killer-demo-(and-train-your-sales-teams-to-do-the-same)

How to deliver a killer demo (and train your sales teams to do the same)

Related Posts