Reading an Excel file in Node.js allows you to extract structured data from .xlsx or .xls files for use in applications like dashboards, data analysis tools, or backend services. This is achieved using a reliable npm package that handles the complexity of Excel’s binary and XML formats. You don’t need to manually parse bytes—just install a package, load the file, and access rows and cells as JavaScript objects.
What You'll Need
- Node.js installed (version 14 or higher)
- A terminal or command prompt
- An Excel file (.xlsx preferred, .xls supported)
- Basic familiarity with npm and JavaScript
Step-by-Step
- Open your terminal or command prompt and navigate to the directory where you want to create your Node.js project. If you don’t have a project yet, create one with
mkdir excel-readerand thencd excel-reader. - Initialize a new Node.js project by running
npm init -y. This creates apackage.jsonfile with default settings. - Install the
xlsxpackage, which is the most widely used and well-maintained library for reading Excel files in Node.js. Runnpm install xlsx. - Create a new JavaScript file in your project folder, such as
read-excel.js. - Place your Excel file in the same folder as
read-excel.jsand name it something likedata.xlsx. Make sure the file is not open in another program like Microsoft Excel, as this may lock the file and prevent reading. - In
read-excel.js, add the following code to load the Excel file:const XLSX = require('xlsx'); const workbook = XLSX.readFile('data.xlsx'); - Extract the first worksheet from the workbook. Most Excel files have one or more sheets. To access the first sheet, use:
const worksheet = workbook.Sheets[workbook.SheetNames[0]]; - Convert the worksheet into a JavaScript array of objects. This makes it easy to work with row-based data:
Theconst data = XLSX.utils.sheet_to_json(worksheet, { header: 1 });{ header: 1 }option tells the library to return an array where each row is an array of values. If you want objects with column headers as keys, use{ header: 1, defval: '' }and then process the first row as headers manually, or use{ header: 1, raw: false }for formatted values. - Log the data to see the result:
console.log(data); - Run the script by typing
node read-excel.jsin your terminal. You should see an array of arrays printed to the console, with each inner array representing a row from the Excel sheet. - To convert the data into a more usable format—like an array of objects with column names as keys—add this after the previous step:
This assumes your first row contains column headers. If not, you can skip this step or customize it.const headers = data[0]; const rows = data.slice(1); const jsonData = rows.map(row => { const obj = {}; headers.forEach((header, index) => { obj[header] = row[index]; }); return obj; }); console.log(jsonData); - For better error handling, wrap the file reading in a try-catch block:
try { const workbook = XLSX.readFile('data.xlsx'); const worksheet = workbook.Sheets[workbook.SheetNames[0]]; const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); console.log(data); } catch (error) { console.error('Error reading Excel file:', error.message); }
Common Mistakes
- Using
sheet_to_jsonwithout theheader: 1option and expecting objects—this returns raw arrays, which can confuse beginners. - Trying to read a password-protected Excel file. The
xlsxlibrary does not support encrypted files. Decrypt the file first using Excel or another tool. - Leaving the Excel file open while running the script. This causes a file lock error on Windows and macOS.
- Assuming all columns have headers. If your first row contains data, not headers, your mapping logic will misalign keys and values.
- Using
.xlsfiles with complex formatting. While supported, .xls files are older and less reliable. Convert to .xlsx for better compatibility.
Tips
- Use
sheet_to_json(worksheet, { defval: '' })to replace empty cells with empty strings instead ofundefined, making data processing more predictable. - For large files (10,000+ rows), consider streaming with
xlsx-streaminstead of loading the entire file into memory. - Validate your Excel file structure before coding: ensure headers are consistent, no merged cells in data rows, and no blank columns interrupting data.
- Use
workbook.SheetNamesto list all sheets and prompt the user or configure which sheet to read dynamically. - Install
eslintand configure it to catch undeclared variables or missing imports early. - Test with a small sample file first—5 rows and 3 columns—before scaling to large datasets.
Troubleshooting
- "Error: File not found" — Double-check the filename spelling and case. File paths are case-sensitive on Linux and macOS. Use
fs.existsSync('data.xlsx')to verify the file exists before reading. - "Unexpected token in JSON" or garbled output — Your Excel file may have non-standard formatting (e.g., merged cells, formulas, or date formats). Open the file in Excel, save it as .xlsx again, and try again.
- Node crashes on large files — The
xlsxlibrary loads everything into memory. For files over 10MB, usexlsx-streamor split the file into smaller chunks. - Dates appear as numbers — Excel stores dates as serial numbers. Use
{ raw: false }insheet_to_jsonto auto-convert them to JavaScript Date objects. If that fails, manually convert usingnew Date((value - 25569) * 86400 * 1000)for Windows Excel serial numbers. - Missing dependencies or errors on install — Ensure you’re using Node.js 14+. Try deleting
node_modulesandpackage-lock.json, then runnpm installagain. - Unicode characters appear as question marks — Ensure your Excel file is saved with UTF-8 encoding. Re-save it in Excel and check the encoding option if available.
Frequently Asked Questions
Can I read Excel files from a URL in Node.js?
Yes, but you must download the file first. Use node-fetch or axios to download the file to a temporary location, then pass the file path to XLSX.readFile().
Does this work with Google Sheets?
No, not directly. You must export the Google Sheet as .xlsx first. There are APIs to access Google Sheets programmatically, but they require OAuth setup and are separate from this method.
Can I write back to Excel files with this library?
Yes. The xlsx library also supports writing. Use XLSX.utils.json_to_sheet() and XLSX.writeFile() to create or overwrite Excel files.
What if my Excel file has multiple sheets?
Loop through workbook.SheetNames and process each sheet individually. Store results in an object keyed by sheet name for easy access.
Is this library safe for production use?
Yes. xlsx is actively maintained, has over 10 million weekly downloads, and is used in enterprise applications. Always validate input data and sanitize outputs to prevent injection risks.
Why do I get empty rows in my output?
Excel files often contain blank rows or hidden formatting. Use sheet_to_json with blankrows: false to skip empty rows entirely.