Skip to content

Real an Excel file in node.js

In this post, you will learn how to read a Microsoft excel file (.xls, .xlsx) in node.js.

Microsoft Excel is the widely used spreadsheet application whose file extensions are .xls, .xlsx. XLSX is a great npm package to read and update excel files in node.js. Here are the steps:

Install XLSX npm package

npm install xlsx

Import xlsx package to your node.js file

const xlsx = require("xlsx");

Read the Excel file

  const spreadsheet = xlsx.readFile('/home/anand/Downloads/data.xlsx');

To read the sheet names

 const sheets = spreadsheet.SheetNames;
  console.log('Sheet Names -- ' + sheets);

//Sheet Names -- Today, Live, Sheet3

To read a specific sheet

 const secondSheet = spreadsheet.Sheets[sheets[1]]; //sheet 1 is index 0

To read a specific cell in a sheet

 const E2 = secondSheet['E2'];

//{ t: 'n', v: 0.624907407407407, w: '2:59:52 PM' }
// Here 2:59:52 PM is the value of the cell

To read all the values in column

 for(let i=2; ;i++) {
    const fifthColumn = secondSheet['E' + i];
    if(!fifthColumn) {
      break;
    }
   console.log('Fifth Column E' + i + ' --- '  + fifthColumn);
 }

Here I read all the values in the fifth column.

Full code:

 const xlsx = require("xlsx");

function readXl() {
  console.log("Reading the spreadsheet..")
  const spreadsheet = xlsx.readFile('/home/anand/Downloads/data.xlsx');
  const sheets = spreadsheet.SheetNames;
  console.log('Sheet Names -- ' + sheets);
  console.log('Raeding second sheet...');
  const secondSheetName = sheets[1];
  const secondSheet = spreadsheet.Sheets[secondSheetName];

  for(let i=2; ;i++) {
    const fifthColumn = secondSheet['E' + i];
    if(!fifthColumn) {
      break;
    }
    console.log('Fifth Column E' + i + ' --- '  + fifthColumn);
  }
  

}
See also  Blocked by CORS policy error - How to fix?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.