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:
✅ 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
✅ 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:
✅ 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?
Example Output:
If your sheet looks like this:
Recommended by LinkedIn
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:
Example Output:
If the parsed data looks like this:
[
["Name", "Age", "City"],
["John", 25, "New York"],
["Jane", 30, "London"]
]
It will render:
✅ 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:
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:
✅ 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:
🛠 Extending the Component:
Here are a couple of ways you can extend your ExcelUpload component:
<input type="file" accept=".xlsx, .xls" multiple onChange={handleFileUpload} />
✅ 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