Categories
React Answers

How to read Excel files in React?

Spread the love

Sometimes, we want to read Excel files in React.

In this article, we’ll look at how to read Excel files in React.

How to read Excel files in React?

To read Excel files in React, we can use the xlsx package.

To install it, we run:

npm i xlsx

Then we can use it by writing:

import React from "react";
import * as XLSX from "xlsx";

export default function App() {
  const onChange = (e) => {
    const [file] = e.target.files;
    const reader = new FileReader();

    reader.onload = (evt) => {
      const bstr = evt.target.result;
      const wb = XLSX.read(bstr, { type: "binary" });
      const wsname = wb.SheetNames[0];
      const ws = wb.Sheets[wsname];
      const data = XLSX.utils.sheet_to_csv(ws, { header: 1 });
      console.log(data);
    };
    reader.readAsBinaryString(file);
  };
  return (
    <div>
      <input type="file" onChange={onChange} />
    </div>
  );
}

We define the onChange function that takes the file from the file input with:

const [file] = e.target.files;

Then we create a FileReader instance to read the file.

We set the reader.onload property to a function that reads the file.

We get the result with:

const bstr = evt.target.result;

Then we have:

const wb = XLSX.read(bstr, { type: "binary" });

to read the Excel file.

Next, we get the sheet name of the first sheet with:

const wsname = wb.SheetNames[0];

And we get the content of the first sheet with:

const ws = wb.Sheets[wsname];

Finally, we convert the Excel data to CSV with:

const data = XLSX.utils.sheet_to_csv(ws, { header: 1 });

And we call reader.readAsBinaryString with file to read the file.

Conclusion

To read Excel files in React, we can use the xlsx package.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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