Node.js: Reading and Parsing Excel (XLSX) Files

Last updated on November 10, 2021 A Goodman Loading... Post a comment

This article shows you how to read and extract content from an Excel (.xlsx) file by using Node.js. Without any further ado, let’s get our hands dirty and start coding.

Getting Things Ready

We are going to work with a simple Excel file that contains some information as follows:

You can download the file to your computer or use your own file:

https://www.kindacode.com/wp-content/uploads/2021/11/KindaCode.com-Example.xlsx.zip

Writing Code

There are many great libraries that can help us easily read Excel files, such as xlsx (SheetJS), exceljs (ExcelJS), node-xlsx (Node XLSX). In the sample project below, we will use xlsx. It’s super popular and supports TypeScript out-of-the-box.

1. Create a new folder named example (the name doesn’t matter and is totally up to you) then initialize a new Node.js project by running:

npm init

2. In your project directory, create a subfolder called src then add an empty index.js file. Copy the Excel file you’ve downloaded before into the src folder.

Here’s the file structure:

.
├── node_modules
├── package-lock.json
├── package.json
└── src
    ├── KindaCode.com\ Example.xlsx
    └── index.js

3. Installing the xlsx package:

npm i xlsx

4. Here’s the code in index.js:

const path = require("path");
const xlsx = require("xlsx");

const filePath = path.resolve(__dirname, "Kindacode.com Example.xlsx");

const workbook = xlsx.readFile(filePath);
const sheetNames = workbook.SheetNames;

// Get the data of "Sheet1"
const data = xlsx.utils.sheet_to_json(workbook.Sheets[sheetNames[0]])

/// Do what you need with the received data
data.map(person => {
  console.log(`${person.Name} is ${person.Age} years old`);
})

5. Test our project:

node src/index.js

Output:

John Doe is 37 years old
Jane Doe is 37 years old
Captain is 72 years old
Voldermort is 89 years old

Conclusion

We’ve written a simple Node.js program to retrieve the data from a sheet of an Excel workbook. If you’d like to explore more new and interesting things about modern Node.js, take a look at the following articles:

You can also check out our Node.js category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles