Node js excel parser

node-xlsx

npm version

npm total downloads

npm monthly downloads

npm license

github main workflow

Features

Straightforward excel file parser and builder.

  • Relies on SheetJS xlsx module to parse/build excel sheets.
  • Built with TypeScript for static type checking with exported types along the
    library.

Install

npm install node-xlsx --save

Quickstart

Parse an xlsx file

import xlsx from 'node-xlsx';
// Or var xlsx = require('node-xlsx').default;

// Parse a buffer
const workSheetsFromBuffer = xlsx.parse(fs.readFileSync(`${__dirname}/myFile.xlsx`));
// Parse a file
const workSheetsFromFile = xlsx.parse(`${__dirname}/myFile.xlsx`);

Build an xlsx file

import xlsx from 'node-xlsx';
// Or var xlsx = require('node-xlsx').default;

const data = [
  [1, 2, 3],
  [true, false, null, 'sheetjs'],
  ['foo', 'bar', new Date('2014-02-19T14:30Z'), '0.3'],
  ['baz', null, 'qux'],
];
var buffer = xlsx.build([{name: 'mySheetName', data: data}]); // Returns a buffer

Custom column width

import xlsx from 'node-xlsx';
// Or var xlsx = require('node-xlsx').default;

const data = [
  [1, 2, 3],
  [true, false, null, 'sheetjs'],
  ['foo', 'bar', new Date('2014-02-19T14:30Z'), '0.3'],
  ['baz', null, 'qux'],
];
const sheetOptions = {'!cols': [{wch: 6}, {wch: 7}, {wch: 10}, {wch: 20}]};

var buffer = xlsx.build([{name: 'mySheetName', data: data}], {sheetOptions}); // Returns a buffer

Spanning multiple rows A1:A4 in every sheets

import xlsx from 'node-xlsx';
// Or var xlsx = require('node-xlsx').default;

const data = [
  [1, 2, 3],
  [true, false, null, 'sheetjs'],
  ['foo', 'bar', new Date('2014-02-19T14:30Z'), '0.3'],
  ['baz', null, 'qux'],
];
const range = {s: {c: 0, r: 0}, e: {c: 0, r: 3}}; // A1:A4
const sheetOptions = {'!merges': [range]};

var buffer = xlsx.build([{name: 'mySheetName', data: data}], {sheetOptions}); // Returns a buffer

Spanning multiple rows A1:A4 in second sheet

import xlsx from 'node-xlsx';
// Or var xlsx = require('node-xlsx').default;

const dataSheet1 = [
  [1, 2, 3],
  [true, false, null, 'sheetjs'],
  ['foo', 'bar', new Date('2014-02-19T14:30Z'), '0.3'],
  ['baz', null, 'qux'],
];
const dataSheet2 = [
  [4, 5, 6],
  [7, 8, 9, 10],
  [11, 12, 13, 14],
  ['baz', null, 'qux'],
];
const range = {s: {c: 0, r: 0}, e: {c: 0, r: 3}}; // A1:A4
const sheetOptions = {'!merges': [range]};

var buffer = xlsx.build([
  {name: 'myFirstSheet', data: dataSheet1},
  {name: 'mySecondSheet', data: dataSheet2, options: sheetOptions},
]); // Returns a buffer

Beware that if you try to merge several times the same cell, your xlsx file will be seen as corrupted.

  • Using Primitive Object Notation Data values can also be specified in a non-abstracted representation.

Examples:

const rowAverage = [[{t: 'n', z: 10, f: '=AVERAGE(2:2)'}], [1, 2, 3]];
var buffer = xlsx.build([{name: 'Average Formula', data: rowAverage}]);

Refer to xlsx documentation for valid structure and values:

  • Format

Troubleshooting

This library requires at least node.js v10. For legacy versions, you can use this workaround before using the lib.

npm i --save object-assign
Object.prototype.assign = require('object-assign');

Contributing

Please submit all pull requests the against master branch. If your unit test contains javascript patches or features,
you should include relevant unit tests. Thanks!

Available scripts

Script Description
start Alias of test:watch
test Run mocha unit tests
test:watch Run and watch mocha unit tests
lint Run eslint static tests
compile Compile the library
compile:watch Compile and watch the library

Authors

Olivier Louvignes

  • http://olouv.com
  • http://github.com/mgcrea

Copyright and license

Apache License 2.0

Copyright (C) 2012-2014  Olivier Louvignes

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

Except where noted, this license applies to any and all software programs and associated documentation files created by the Original Author and distributed with the Software:

Inspired by SheetJS gist examples, Copyright (c) SheetJS.

exceljs

excel4node

excel4node

Node module to allow for easy Excel file creation

NodeJS excel file parser & builder

xlsx-populate

Excel XLSX parser/generator written in JavaScript with Node.js and browser support, jQuery/d3-style method chaining, encryption, and a focus on keeping existing workbook features and styles in tact.

xlsx-style

xlsx-style

XLSX / XLSM / XLSB (Excel 2007+ Spreadsheet) / ODS parser and writer

js-xlsx

js-xlsx

XLSX / XLSM / XLSB (Excel 2007+ Spreadsheet) / ODS parser and writer

excel

Native node.js Excel file parser. Only supports xlsx for now.

Useful link

Read Excel Files and convert to JSON in Node.js

 var express = require('express'); 
    var app = express(); 
    var bodyParser = require('body-parser');
    var multer = require('multer');
    var xlstojson = require("xls-to-json-lc");
    var xlsxtojson = require("xlsx-to-json-lc");
    app.use(bodyParser.json());
    var storage = multer.diskStorage({ //multers disk storage settings
        destination: function (req, file, cb) {
            cb(null, './uploads/')
        },
        filename: function (req, file, cb) {
            var datetimestamp = Date.now();
            cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
        }
    });
    var upload = multer({ //multer settings
                    storage: storage,
                    fileFilter : function(req, file, callback) { //file filter
                        if (['xls', 'xlsx'].indexOf(file.originalname.split('.')[file.originalname.split('.').length-1]) === -1) {
                            return callback(new Error('Wrong extension type'));
                        }
                        callback(null, true);
                    }
                }).single('file');
    /** API path that will upload the files */
    app.post('/upload', function(req, res) {
        var exceltojson;
        upload(req,res,function(err){
            if(err){
                 res.json({error_code:1,err_desc:err});
                 return;
            }
            /** Multer gives us file info in req.file object */
            if(!req.file){
                res.json({error_code:1,err_desc:"No file passed"});
                return;
            }
            /** Check the extension of the incoming file and 
             *  use the appropriate module
             */
            if(req.file.originalname.split('.')[req.file.originalname.split('.').length-1] === 'xlsx'){
                exceltojson = xlsxtojson;
            } else {
                exceltojson = xlstojson;
            }
            try {
                exceltojson({
                    input: req.file.path,
                    output: null, //since we don't need output.json
                    lowerCaseHeaders:true
                }, function(err,result){
                    if(err) {
                        return res.json({error_code:1,err_desc:err, data: null});
                    } 
                    res.json({error_code:0,err_desc:null, data: result});
                });
            } catch (e){
                res.json({error_code:1,err_desc:"Corupted excel file"});
            }
        })
    }); 
    app.get('/',function(req,res){
        res.sendFile(__dirname + "/index.html");
    });
    app.listen('3000', function(){
        console.log('running on 3000...');
    });

Cover image for How to parse an Excel file in Node.js

This is a short introduction to reading and parsing Excel (xls, xlsx) files in Node.js. We will be using the npm module «xlsx» (SheetJS) for this example.

Top comments (0)

For further actions, you may consider blocking this person and/or reporting abuse

Read next


cteyton profile image

How a start-up implemented hexagonal architecture – The case of Promyze

Cédric Teyton — Mar 27


fritzlolpro profile image

Rust-Based Web Development Tools — The Future of Infrastructure, but be cautious!

Fedor — Apr 5


ben profile image

Tech Industry Burnout: How Can We Prevent It?

Ben Halpern — Apr 11


tyagi_data_wizard profile image

Document or Die: The Importance of Writing Things Down in Tech

Ujjwal Tyagi — Apr 10

Once suspended, coder4_life will not be able to comment or publish posts until their suspension is removed.

Once unsuspended, coder4_life will be able to comment and publish posts again.

Once unpublished, all posts by coder4_life will become hidden and only accessible to themselves.

If coder4_life is not suspended, they can still re-publish their posts from their dashboard.

Note:

Once unpublished, this post will become invisible to the public and only accessible to coder4life.

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community safe. Here is what you can do to flag coder4_life:

Make all posts by coder4_life less visible

coder4_life consistently posts content that violates DEV Community’s
code of conduct because it is harassing, offensive or spammy.

Unflagging coder4_life will restore default visibility to their posts.

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 from the link below to your computer:

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. Below are the code snippets for index.js. There are 2 different code snippets. The first one uses the CommonJS syntax (with require), while the second one uses the ES Modules syntax (with import). Choose the one that fits your need.

CommonJS:

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`);
})

ES Modules:

// import with ES6 Modules syntax
import path from 'path';
import xlsx from 'xlsx';

import { fileURLToPath } from 'url'
import { dirname } from 'path'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

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:

  • Node.js: How to Ping a Remote Server/ Website
  • Best open-source ORM and ODM libraries for Node.js
  • 7 Best Open-Source HTTP Request Libraries for Node.js
  • Node.js: Executing a Piece of Code after a Delay
  • Express + TypeScript: Extending Request and Response objects

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

Node.js is an open-source and cross-platform JavaScript runtime environment that can also be used to read from a file and write to a file which can be in txt, ods, xlsx, docx, etc format.

The following example covers how an excel file(.xlsx) file is read from an excel file and then converted into JSON and also to write to it. It can be achieved using a package called xlsx to achieve our goal.

Module Installation: You can install xlsx module using the following command:

npm install xlsx

Note: For the following example, text.xlsx is a dummy data file that has been used.

Filename: test.xlsx 

Sheet 1:

Sheet 2:

So the excel file test.xlsx has 2 sheets, one having Student details and another having lecturer details.

Read Operation Filename: read.js 

Javascript

const reader = require('xlsx')

const file = reader.readFile('./test.xlsx')

let data = []

const sheets = file.SheetNames

for(let i = 0; i < sheets.length; i++)

{

   const temp = reader.utils.sheet_to_json(

        file.Sheets[file.SheetNames[i]])

   temp.forEach((res) => {

      data.push(res)

   })

}

console.log(data)

Explanation: First, the npm module is included in the read.js file and then the excel file is read into a workbook i.e constant file in the above program.

The number of files in that particular excel file is available in the SheetNames property of the workbook. It can be accessed as follows:

const sheets = file.SheetNames  // Here the value of the sheets will be 2

A for loop is run until the end of the excel file starting from the first page. One of the most important functions used in the code above is the sheet_to_json() function present in the utils module of the xlsx package. It accepts a worksheet object as a parameter and returns an array of JSON objects.

There is a forEach loop which iterates through every JSON object present in the array temp and pushes it into a variable data which would contain all the data in JSON format.

Finally, the data is printed or any other modification can be performed on the array of JSON objects.

Step to run the application:

Run the read.js file using the following command:

node read.js

Output:

Write Operation In the following example, we will convert an array of JSON objects into an excel sheet and append it to the file.

Filename: write.js

Javascript

const reader = require('xlsx')

const file = reader.readFile('./test.xlsx')

let student_data = [{

    Student:'Nikhil',

    Age:22,

    Branch:'ISE',

    Marks: 70

},

{

    Student:'Amitha',

    Age:21,

    Branch:'EC',

    Marks:80

}]

const ws = reader.utils.json_to_sheet(student_data)

reader.utils.book_append_sheet(file,ws,"Sheet3")

reader.writeFile(file,'./test.xlsx')

Explanation: Here we have an array of JSON objects called student_data. We use two main functions in this program i.e json_to_sheet() which accepts an array of objects and converts them into a worksheet and another function is the book_append_sheet() to append the worksheet into the workbook.

Finally, all the changes are written to the test.xlsx file using writeFile() function which takes a workbook and a excel file as input parameter.

Step to run the application:

Run the read.js file using the following command:

node write.js

Output: The final test.xlsx file would look something like this: 

Sheet 1:

Sheet 2:

Sheet 3: We can see sheet 3 is appended into the test.xlsx as shown below:

Понравилась статья? Поделить с друзьями:
  • No word for fun in russian
  • Node js excel import
  • Node js excel export
  • Node js create excel
  • Node js and excel