DEV Community

Cover image for How to read XLS Spreadsheets with React js.
Abdulsamad Ajao
Abdulsamad Ajao

Posted on

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,
Node and npm installed on your system.

Step 1
Install Sheet JS.

npm install xlsx
Enter fullscreen mode Exit fullscreen mode

Step 2
Import Sheet js into your jsx file.

import * as XLSX from 'xlsx';
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

Utilize the readAsBinaryString method to initiate the reading process for the specified file from the event argument.

reader.readAsBinaryString(e.target.files[0]);
Enter fullscreen mode Exit fullscreen mode

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})
    };
Enter fullscreen mode Exit fullscreen mode

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})
    };
Enter fullscreen mode Exit fullscreen mode

Leave a like if this helped, Thanks
Happy Coding!

Top comments (1)

Collapse
 
sammybammy52 profile image
Seye Yemi-Olowolabi

great tutorial