How To Read Excel File In React Js

The reading of an excel file in React is demonstrated in this post. We start from scratch and build a React application to read the excel file.

Get Started:

Step 1:
Set up a new React Application

npx create-react-app read-excel

Change your directory…

cd read-excel

And run your project to check its successfully created or not?

npm start

Step 2:
Install ‘xlsx’ package in your application.

npm i xlsx

Then import it into your App.js file.

import * as XLSX from "xlsx";

Step 3:
Add the following HTML for get the file.

<input
        type="file"
        placeholder="Upload file"
        accept=".csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
        onChange={(event) => {
          addfile(event)
        }}
/>

Step 4:
Add the method for handle file input.

function addfile(event) {
  let file = event.target.files[0];
  let fileReader = new FileReader();
  fileReader.readAsArrayBuffer(file);
  fileReader.onload = (e) => {
    let arrayBuffer = fileReader.result;
    var data = new Uint8Array(arrayBuffer);
    var arr = new Array();
    for (var i = 0; i != data.length; ++i)
      arr[i] = String.fromCharCode(data[i]);
    var bstr = arr.join("");
    var workbook = XLSX.read(bstr, { type: "binary" });
    var first_sheet_name = workbook.SheetNames[0];
    var worksheet = workbook.Sheets[first_sheet_name];
    console.log(XLSX.utils.sheet_to_json(worksheet, { raw: true }));
    var arraylist = XLSX.utils.sheet_to_json(worksheet, { raw: true });
  };
}

Now, run your project, upload an excel file and check the output in the console.

Submit a Comment

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

Subscribe

Select Categories