How To Read Excel File In React.js

In this article, we will learn how to read data from Excel file in React JS.

Prerequisites:

  • Have Created React app

Step 1 : Import the following package in your app to read Excel File.

npm install xlsx

Step 2 : Navigate to your component and add the below code:

import React from 'react'
import { useState } from 'react';
import { read, utils, writeFile } from 'xlsx';

const HomeComponents = () => {
    const [data, setdata] = useState([])

    const readfile = ($event) => {
        const files = $event.target.files;
        if (files.length) {
            const file = files[0];
            const reader = new FileReader();
            reader.onload = (event) => {
                const wb = read(event.target.result);
                const sheets = wb.SheetNames;

                if (sheets.length) {
                    const rows = utils.sheet_to_json(wb.Sheets[sheets[0]]);
                    setdata(rows)
                }
            }
            reader.readAsArrayBuffer(file);
        }
    }
    return (
        <div style={{ marginTop: '30px' }}>
            <input type='file' onChange={readfile} accept='.xlsx' />

            <table style={{ margin: '20px auto' }}>
                <tr>
                    <th>Employee Code</th>
                    <th>Name</th>
                    <th>Position</th>
                    <th>Contact No.</th>
                </tr>
                {
                    data.map(x => {
                        return <tr>
                            <td>{x.employee_code}</td>
                            <td>{x.name}</td>
                            <td>{x.position}</td>
                            <td>{x.contact}</td>
                        </tr>
                    })
                }
            </table>
        </div>
    )
}

export default HomeComponents

– Add the following CSS to your App.css for styling the table

table, th, td {
  border: 1px solid white;
  border-collapse: collapse;
}
th, td {
  background-color: #96D4D4;
  padding: 5px;
}

– Here I have attached a video for Reference

– Sample Excel File :

– Hope you learn how to read data from an excel file in React.js.

-If you have any doubt feel free to ask in the comment section.

Submit a Comment

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

Subscribe

Select Categories