Create a Reusable Excel Import Component in React for Any Project

Create a Reusable Excel Import Component in React for Any Project

TL;DR

Learn how to build a simple and reusable Excel import component in React using the xlsx and FileReader APIs. This guide walks you through setup, file parsing, data display, and handling errors — all with clean and reusable code.


Why You Need an Excel Import Feature in React

In many business apps — dashboards, CRMs, reporting tools, or admin panels — uploading Excel files is a must-have. Instead of manually entering hundreds of rows, users can simply upload .xlsx or .xls files and get data populated instantly.

React, being flexible and component-based, is perfect for creating a reusable file upload feature. Whether you're building a one-off internal tool or a scalable SaaS dashboard, this feature helps streamline data input while reducing user error.

Real-world examples where Excel upload helps:

  • Importing customer data into a CRM
  • Uploading bulk employee records in an HRMS
  • Uploading leads, budgets, or transactions in admin panels

Tip: A reusable component saves time, avoids repetitive code, and keeps your project clean.


What You’ll Need to Get Started

Before writing code, make sure your environment is ready. You’ll only need a few things to get going:

🧰 Tools and Libraries

  • React – Set up using Create React App or any boilerplate of your choice.
  • XLSX – A powerful JavaScript library for reading and writing Excel files.
  • FileReader API – Built-in browser API to read files locally.

✅ Tip:

Make sure to use .xlsx files for best compatibility with the XLSX parser.


Install the Required Packages

Let’s install the libraries you’ll need to handle Excel uploads in your React project.

📦 Step-by-Step Installation

Open your terminal and run the following commands inside your React project folder:

npm install xlsx        

That’s it! The xlsx library gives you all the tools to read, parse, and manipulate Excel files.

🛠 Optional (for file input styling)

You can also install a UI library (like Material-UI, Bootstrap, or Tailwind) if you want a more polished file input. But for this guide, we’ll keep it simple with basic HTML.

Tip: Use xlsx instead of older Excel parsers. It supports both .xls and .xlsx and works reliably in most browsers.


Designing the Excel Upload Component

Now that we’ve installed the necessary packages, let’s dive into building the core of the component: the Excel Upload Feature. The goal is to design a simple, reusable component that can be used across different projects.

✨ Component Design

First, let’s create a new functional component, ExcelUpload.js, where the user will upload their file.

Here’s how we can design it:

import React, { useState } from 'react';
import * as XLSX from 'xlsx';

const ExcelUpload = ({ onDataParsed }) => {
  const [fileName, setFileName] = useState('');

  const handleFileUpload = (e) => {
    const file = e.target.files[0];

    if (file) {
      setFileName(file.name);
      const reader = new FileReader();
      reader.onload = (evt) => {
        const binaryString = evt.target.result;
        const workbook = XLSX.read(binaryString, { type: 'binary' });

        // Assume we're importing the first sheet
        const sheet = workbook.Sheets[workbook.SheetNames[0]];
        const data = XLSX.utils.sheet_to_json(sheet, { header: 1 });

        onDataParsed(data);  // Pass data to parent component
      };
      reader.readAsBinaryString(file);
    }
  };

  return (
    <div>
      <input type="file" accept=".xlsx, .xls" onChange={handleFileUpload} />
      {fileName && <p>File selected: {fileName}</p>}
    </div>
  );
};

export default ExcelUpload;        

Key Points to Note:

  • FileReader API is used to read the file as binary, which is necessary for xlsx to parse it.
  • The Excel sheet is converted into a JSON format, making it easy to display or use in your application.
  • The onDataParsed function is a callback function that will be passed from the parent component, so the uploaded data can be processed or displayed.

Tip: Keeping the component simple with just one sheet at a time makes it easier to extend later if you need to handle multiple sheets or more complex file types.


Reading and Parsing Excel Files

Now that the user can upload an Excel file, we need to read and parse the contents into a usable format. In this section, we’ll focus on converting the raw data from the Excel file into a clean JSON format.

📊 Parsing the Excel Data

The XLSX.utils.sheet_to_json method is key here. It converts an Excel sheet into an array of JavaScript objects, where each object represents a row of data.

Here’s how we do that in the handleFileUpload function from earlier:

const workbook = XLSX.read(binaryString, { type: 'binary' });
// Get the first sheet from the workbook
const sheet = workbook.Sheets[workbook.SheetNames[0]];
// Convert the sheet to JSON
const data = XLSX.utils.sheet_to_json(sheet, { header: 1 });         

Why use header: 1?

  • This setting treats the first row of the sheet as a header and will map the data accordingly. For example, if the first row contains column names like Name, Age, etc., the resulting JSON will use these as the keys.

Example Output:

If your sheet looks like this:


Article content

The output from sheet_to_json will be:

[
  ["Name", "Age", "City"],
  ["John", 25, "New York"],
  ["Jane", 30, "London"]
]        

Tip: If your data has specific formats (e.g., dates), you can use additional XLSX utilities to format it before passing it along.


Showing the Uploaded Data to Users

Once the Excel data is parsed and ready, it’s time to display it in a user-friendly way. For this, we’ll render the data in a simple HTML table.

📊 Displaying the Data

We can update the ExcelUpload component to display the parsed data once it’s available. Here’s how to render it:

import React, { useState } from 'react';
import * as XLSX from 'xlsx';

const ExcelUpload = ({ onDataParsed }) => {
  const [fileName, setFileName] = useState('');
  const [excelData, setExcelData] = useState([]);

  const handleFileUpload = (e) => {
    const file = e.target.files[0];
    if (file) {
      setFileName(file.name);
      const reader = new FileReader();
      reader.onload = (evt) => {
        const binaryString = evt.target.result;
        const workbook = XLSX.read(binaryString, { type: 'binary' });
        const sheet = workbook.Sheets[workbook.SheetNames[0]];
        const data = XLSX.utils.sheet_to_json(sheet, { header: 1 });
        setExcelData(data);
        onDataParsed(data);
      };
      reader.readAsBinaryString(file);
    }
  };

  return (
    <div>
      <input type="file" accept=".xlsx, .xls" onChange={handleFileUpload} />
      {fileName && <p>File selected: {fileName}</p>}

      <table border="1">
        <thead>
          <tr>
            {excelData[0] && excelData[0].map((header, index) => (
              <th key={index}>{header}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {excelData.slice(1).map((row, rowIndex) => (
            <tr key={rowIndex}>
              {row.map((cell, cellIndex) => (
                <td key={cellIndex}>{cell}</td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

export default ExcelUpload;        

Key Details:

  • We store the parsed data in a state variable excelData.
  • The first row (excelData[0]) contains the column names (header), so we loop through it to create the table headers.
  • The remaining rows are displayed as table rows.

Example Output:

If the parsed data looks like this:

[
  ["Name", "Age", "City"],
  ["John", 25, "New York"],
  ["Jane", 30, "London"]
]        

It will render:


Article content

Tip: Consider adding pagination or sorting if the dataset is large.


Handling File Errors and Validations

To ensure a smooth user experience, we should add basic file validation. This will prevent errors like uploading non-Excel files or very large files that might break your app.

✅ Common File Validations:

  1. Check for File Type We only want to allow .xlsx or .xls files. You can easily check this by inspecting the file extension.
  2. Limit File Size You might want to limit the file size (e.g., 5MB) to ensure performance isn’t impacted.
  3. Handle Missing or Corrupt Files Display a user-friendly message if something goes wrong with the file processing.

Here’s how to add these checks to your handleFileUpload function:

const handleFileUpload = (e) => {
  const file = e.target.files[0];

  // Validate file type
  const fileExtension = file.name.split('.').pop();
  if (fileExtension !== 'xlsx' && fileExtension !== 'xls') {
    alert('Please upload an Excel file (.xlsx or .xls)');
    return;
  }

  // Validate file size (limit to 5MB)
  if (file.size > 5 * 1024 * 1024) {
    alert('File size exceeds the 5MB limit.');
    return;
  }

  // Proceed with reading the file
  setFileName(file.name);
  const reader = new FileReader();
  reader.onload = (evt) => {
    try {
      const binaryString = evt.target.result;
      const workbook = XLSX.read(binaryString, { type: 'binary' });
      const sheet = workbook.Sheets[workbook.SheetNames[0]];
      const data = XLSX.utils.sheet_to_json(sheet, { header: 1 });
      setExcelData(data);
      onDataParsed(data);
    } catch (error) {
      alert('Error reading the Excel file. Please check the file format.');
    }
  };
  reader.readAsBinaryString(file);
};        

Key Validations:

  • File Type: We ensure the file is either .xlsx or .xls.
  • File Size: We limit file size to 5MB to keep things manageable.
  • Error Handling: If reading or parsing the file fails, we alert the user with a helpful message.

Tip: You can always enhance validation by adding more checks (e.g., verifying sheet structure or specific data types in columns).


Tips to Reuse and Extend the Component

Now that we’ve built the basic Excel upload component, let’s talk about how you can reuse and extend it for different use cases.

🔄 Reusability Tips:

  1. Pass Custom Callbacks: The component currently passes the parsed data to the parent via onDataParsed. You can extend this by adding more callbacks for error handling, progress tracking, etc.
  2. Support Multiple Sheets: By default, the component reads only the first sheet. To handle multiple sheets, you could update the component to allow the user to select which sheet they want to import.
  3. Custom File Inputs: You might want to replace the default file input with a custom-designed button, or even drag-and-drop functionality. Libraries like react-dropzone can be helpful here.
  4. Styled UI: To enhance the user experience, you can integrate UI frameworks like Material-UI or Tailwind CSS to style the component. It’ll make the file input more visually appealing and professional.

🛠 Extending the Component:

Here are a couple of ways you can extend your ExcelUpload component:

  • Multiple File Uploads: Update the component to allow users to upload more than one Excel file at a time.

<input type="file" accept=".xlsx, .xls" multiple onChange={handleFileUpload} />        

  • File Preview: Add a preview of the Excel content before parsing. You could display the first few rows as a preview, letting the user confirm before parsing the entire file.
  • Add Progress Bar: If your files are large, adding a progress bar will make the process feel smoother. You can use the FileReader API’s onprogress event to track the reading progress.

Tip: Start simple and add features incrementally. Build out core functionality first, then add enhancements as needed.


Wrapping Up

You’ve now built a reusable Excel import component in React that can be easily adapted to fit any project! From uploading to parsing and displaying Excel data, this component can save you time and provide a clean user experience.


Created with help of Chat GPT

To view or add a comment, sign in

More articles by Srikanth R

Insights from the community

Others also viewed

Explore topics