Master Excel File Handling in Node.js with js-xlsx and excel-export

This guide compares popular Node.js npm packages for Excel file handling, recommends using js‑xlsx for parsing and excel‑export for generation, and provides detailed installation steps, core concepts, code examples, and a complete workflow for reading, converting to JSON, and writing Excel files on both server and browser environments.

Aotu Lab
Aotu Lab
Aotu Lab
Master Excel File Handling in Node.js with js-xlsx and excel-export

Introduction

The article introduces using Node.js libraries to process Excel files, compares common npm packages, and focuses on the practical use of js-xlsx for parsing and excel-export for generating Excel files.

Approach

Identify external modules that support reading and writing Excel.

Import the required dependencies.

Write business‑logic functions.

Apply the solution in a real‑world scenario.

Node.js modules for Excel

Commonly used npm packages include:

js-xlsx : Most starred library on GitHub, supports multiple formats (XLSX, XLSM, XLSB, XLS, CSV). Writing requires FileSaver.js. Powerful but has a steeper learning curve.

node-xlsx : Parses and generates Excel files but only supports the XLSX format.

excel-parser : Supports XLS and XLSX but depends on Python, making it heavy.

excel-export : Generates XLSX files, allows setting column widths, easy API, but cannot create worksheet sub‑tables.

node-xlrd : Extracts data from XLS files only; outdated.

Preferred combination

The author recommends combining js-xlsx for reading/parsing and excel-export for writing, leveraging the strengths of each library.

Lesson 1: Using js-xlsx

Installation

$ npm install xlsx

Browser usage: include <script src="dist/xlsx.core.min.js"></script> (or the full build dist/xlsx.full.min.js for all features). Bower installation: bower install js-xlsx.

Key concepts

Three core objects:

workbook : Represents the entire Excel document.

worksheet : Represents a single sheet within the workbook.

cell : Represents an individual cell in a worksheet.

// workbook example
{
  SheetNames: ['sheet1', 'sheet2'],
  Sheets: {
    'sheet1': {
      'A1': { /* ... */ },
      'A2': { /* ... */ }
    },
    'sheet2': { /* ... */ }
  }
}

Basic usage

Read an Excel file with XLSX.read (buffer) or XLSX.readFile (path) to obtain a workbook.

Get sheet names via workbook.SheetNames.

Access a worksheet with workbook.Sheets[sheetName].

Read a cell using worksheet[address].

Convert a worksheet to JSON with XLSX.utils.sheet_to_json.

Write a new file with XLSX.writeFile(wb, 'output.xlsx').

Advanced example: Convert workbook to JSON

function to_json(workbook) {
  var result = {};
  var sheetNames = workbook.SheetNames;
  workbook.SheetNames.forEach(function(sheetName) {
    var worksheet = workbook.Sheets[sheetName];
    result[sheetName] = XLSX.utils.sheet_to_json(worksheet);
  });
  console.log("Print sheet info", JSON.stringify(result, 2, 2));
  return result;
}

Exporting a workbook

Construct a workbook object, ensure the !ref range is defined, then write the file. In the browser, use XLSX.write together with FileSaver to trigger a download.

// Example of building a workbook and saving in the browser
var wopts = { bookType:'xlsx', bookSST:false, type:'binary' };
var wbout = XLSX.write(wb, wopts);
function s2ab(s) {
  var buf = new ArrayBuffer(s.length);
  var view = new Uint8Array(buf);
  for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  return buf;
}
saveAs(new Blob([s2ab(wbout)], {type:""}), "test.xlsx");

Lesson 2: Using excel-export

excel-export

provides a straightforward API for generating XLSX files, allowing column width configuration and cell type specification. The following example creates an Express route that builds a spreadsheet and streams it to the client.

var express = require('express');
var nodeExcel = require('excel-export');
var app = express();

app.get('/Excel', function(req, res){
  var conf = {};
  conf.stylesXmlFile = "styles.xml";
  conf.name = "mysheet";
  conf.cols = [
    {caption:'string', type:'string', width:28.71, beforeCellWrite:function(row,cellData){return cellData.toUpperCase();}},
    {caption:'date', type:'date', beforeCellWrite:function(){ /* date conversion logic */ }},
    {caption:'bool', type:'bool'},
    {caption:'number', type:'number'}
  ];
  conf.rows = [
    ['pi', new Date(Date.UTC(2013,4,1)), true, 3.14],
    ["e", new Date(Date.UTC(2012,4,1)), false, 2.7182],
    ["M&M<>", new Date(Date.UTC(2013,6,9)), false, 1.61803],
    ["null date", null, true, 1.414]
  ];
  var result = nodeExcel.execute(conf);
  res.setHeader('Content-Type','application/vnd.openxmlformats');
  res.setHeader('Content-Disposition',"attachment; filename=Report.xlsx");
  res.end(result,'binary');
});
app.listen(3000);
console.log('Listening on port 3000');

excel-export workflow

Configure the Excel file name ( conf.name).

Define column captions, data types, and widths ( conf.cols).

Populate rows ( conf.rows) and generate the file with nodeExcel.execute.

Send the generated binary data to the client with appropriate headers.

Conclusion

The article offers a practical comparison of npm Excel libraries and step‑by‑step code samples for both reading (js‑xlsx) and writing (excel‑export) Excel files in Node.js, covering installation, core concepts, API usage, and complete end‑to‑end examples for server‑side and browser environments.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaScriptNode.jsexcel-exportExceljs-xlsx
Aotu Lab
Written by

Aotu Lab

Aotu Lab, founded in October 2015, is a front-end engineering team serving multi-platform products. The articles in this public account are intended to share and discuss technology, reflecting only the personal views of Aotu Lab members and not the official stance of JD.com Technology.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.