Comprehensive Guide to Node xlsx for Effortless Excel File Manipulation with Code Snippets

Introduction to Node-xlsx

In this article, we delve into the world of node-xlsx, a powerful library for manipulating Excel files in Node.js. You will explore various APIs and see practical examples of creating, reading, and modifying Excel files. Let’s start with some key features and numerous examples.

Installing Node-xlsx

  
  npm install node-xlsx
  

Creating a Simple Excel File

  
  const xlsx = require('node-xlsx').default;
  const fs = require('fs');

  const data = [
    ["Name", "Age", "Gender"],
    ["John Doe", 30, "Male"],
    ["Jane Smith", 28, "Female"]
  ];

  const buffer = xlsx.build([{ name: "Sheet1", data }]);
  fs.writeFileSync('example.xlsx', buffer);
  

Reading an Excel File

  
  const xlsx = require('node-xlsx').default;
  const fs = require('fs');

  const buffer = fs.readFileSync('example.xlsx');
  const worksheets = xlsx.parse(buffer);

  worksheets.forEach(sheet => {
    console.log(`Sheet: ${sheet.name}`);
    sheet.data.forEach(row => {
      console.log(row);
    });
  });
  

Modifying an Excel File

  
  const xlsx = require('node-xlsx').default;
  const fs = require('fs');

  // Read data
  const buffer = fs.readFileSync('example.xlsx');
  const worksheets = xlsx.parse(buffer);

  // Modify data
  worksheets[0].data.push(["New Person", 22, "Non-binary"]);

  // Write data back to file
  const newBuffer = xlsx.build(worksheets);
  fs.writeFileSync('example_modified.xlsx', newBuffer);
  

Create a Simple Application with Node-xlsx

   
   const express = require('express');
   const xlsx = require('node-xlsx').default;
   const fs = require('fs');

   const app = express();

   app.get('/download', (req, res) => {
     const data = [
       ["Name", "Age", "Gender"],
       ["John Doe", 30, "Male"]
     ];

     const buffer = xlsx.build([{ name: "Sheet1", data }]);

     res.setHeader('Content-Disposition', 'attachment; filename="example.xlsx"');
     res.send(buffer);
   });

   app.listen(3000, () => {
     console.log('Server started on http://localhost:3000');
   });
   

Conclusion

There you have it! A comprehensive guide to using node-xlsx for creating, reading, and modifying Excel files in your Node.js applications. Whether you are working on a small project or a large-scale application, node-xlsx can make Excel file manipulation effortless. Give it a try and see the difference it makes in your development workflow!

Hash: a1a9ac13efba05fb59af12b231315a074329d4fe632ec88681376deca0a90c48

Leave a Reply

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