To read an Excel file in React JS, you use a library like SheetJS (xlsx) to parse .xlsx or .xls files uploaded by users, convert them into JavaScript objects, and display or process the data in your app. This enables dynamic data handling without backend servers, ideal for dashboards, import tools, or configuration panels. No server-side code is needed—just a frontend library and a file input.

What You'll Need

  • React JS project (created with Create React App, Vite, or similar)
  • SheetJS library (xlsx) installed via npm or yarn
  • A basic understanding of React hooks (useState, useEffect)
  • An Excel file (.xlsx or .xls) for testing

Step-by-Step

  1. Open your terminal or command prompt in your React project directory and install SheetJS by running: npm install xlsx or yarn add xlsx. This adds the library to your node_modules and package.json.
  2. In the component where you want to read the file (e.g., App.js or a dedicated ExcelReader.js), import the library at the top: import * as XLSX from 'xlsx';.
  3. Create a state variable to store the parsed data using useState. For example: const [data, setData] = useState([]);. This will hold your Excel rows as arrays of objects.
  4. Write a function to handle file selection. Use an <input type="file" accept=".xlsx,.xls" /> element in your JSX. Add an onChange handler: onChange={handleFileUpload}.
  5. Define the handleFileUpload function. Inside it, use event.target.files[0] to get the selected file. Create a FileReader object to read the file as an array buffer: const reader = new FileReader();.
  6. Set the FileReader’s onload event to process the file. Inside the event handler, use XLSX.read(reader.result, { type: 'array' }); to parse the binary data into a workbook object.
  7. Extract the first worksheet from the workbook using const worksheet = workbook.Sheets[workbook.SheetNames[0]];. This assumes you’re reading the first sheet—adjust if needed.
  8. Convert the worksheet to a JavaScript array of objects using XLSX.utils.sheet_to_json(worksheet, { header: 1 });. The { header: 1 } option returns arrays with row values. For object format (keyed by column headers), use { header: 1, defval: "" } and then map to objects later.
  9. If you used header: 1, convert the array to objects by using the first row as headers. For example: extract the first row as headers, then map each subsequent row into an object using those keys. Store the result in your state: setData(parsedData);.
  10. Render the data in your JSX. Use {data.map((row, index) => <div key={index}>{row.join(', ')} to display rows, or build a table with <table> and <tr> elements for structured output.
  11. Test by uploading a sample Excel file with at least two rows and two columns. Check the browser console for any parsing errors or malformed data.

Common Mistakes

  • Forgetting to install the xlsx library—this causes "Cannot find module 'xlsx'" errors.
  • Using header: true instead of header: 1 when the first row isn’t clean headers (e.g., has merged cells or blank cells), which leads to undefined keys.
  • Not checking if event.target.files exists before accessing [0], causing "Cannot read property '0' of undefined" when no file is selected.
  • Assuming Excel files always have a single sheet; if multiple sheets exist and you only read the first, you’ll miss data.
  • Trying to parse .csv files with SheetJS without converting them first—SheetJS handles Excel formats only, not raw CSV.
  • Not handling empty or malformed cells, which can cause JavaScript errors when mapping to objects. Always use defensive coding like defval: "" in sheet_to_json.

Tips

  • Use { header: 1, defval: "" } to ensure every cell has a value, avoiding nulls that break rendering.
  • For large files (>10k rows), consider pagination or virtual scrolling—SheetJS can freeze the UI on heavy parsing.
  • Validate file type before parsing: check file.name.endsWith('.xlsx') || file.name.endsWith('.xls') to avoid errors from non-Excel files.
  • Display a loading spinner while parsing large files to improve UX.
  • Use workbook.SheetNames to let users select which sheet to read if your app supports multi-sheet Excel files.
  • Store parsed data in localStorage for quick re-access if the user re-opens the same file, reducing reload time.
  • Test with real-world Excel files: include merged cells, formulas, dates, and currency formats to see how SheetJS handles them—dates are often converted to numbers, so you may need to format them manually.

Troubleshooting

  • "Uncaught TypeError: Cannot read property 'Sheets' of undefined": The file didn’t parse. Check that the file is a valid .xlsx or .xls. Try opening it in Excel to confirm it’s not corrupted.
  • File input doesn’t trigger onChange : Make sure the input has the correct type="file" and you’re binding the handler correctly with (not ).
  • Data appears as numbers instead of dates: SheetJS converts Excel dates to serial numbers. Use XLSX.utils.format_date() or manually convert using new Date((num - 25569) * 86400 * 1000) to get a JavaScript Date object.
  • React says "Invalid hook call": You’re likely using a hook outside a functional component. Ensure your code using useState is inside a component function, not a class or utility file.
  • Empty array returned: The worksheet might be empty or the sheet name is wrong. Log workbook.SheetNames to confirm the sheet exists and is named as expected.
  • Performance is slow: Break large files into chunks using Web Workers, or limit parsing to the first 100 rows during development for faster feedback.

Frequently Asked Questions

Can I read Excel files without using SheetJS?

Yes, but it’s not practical. Other libraries like exceljs or papaparse exist, but SheetJS is the most widely used and supports both .xlsx and .xls with minimal setup. Avoid writing raw parsers—Excel binary format is complex.

Does this work on mobile browsers?

Yes, as long as the mobile browser supports the File API and FileReader (all modern iOS Safari and Android Chrome do). Test on target devices, as some file pickers may restrict file types.

Can I write data back to Excel?

Yes, SheetJS can also generate Excel files. Use XLSX.utils.json_to_sheet() to create a worksheet, then XLSX.writeFile() to trigger a download. This requires no server.

What if my Excel has formulas?

SheetJS reads the calculated result, not the formula itself. If you need the formula, use { cellDates: true, raw: true } in sheet_to_json to access raw values. Formulas are not preserved in the output.

Can I read password-protected Excel files?

No. SheetJS cannot decrypt password-protected workbooks. You must remove the password externally before uploading.

Why are my dates wrong after parsing?

Excel uses a different epoch than JavaScript. Dates are stored as serial numbers starting from January 1, 1900. Convert them using: new Date((value - 25569) * 86400 * 1000) for Windows Excel files. Mac Excel uses a different offset—check your source system.