Read and write data in xlxs using node js

 

Read  and write data in xlxs using node js



  Here is our Excel file containing fields:

Name                Age
Ajay    23
Akshay25
Anand28





Let's start,

Step 1: Install node js using the following command.

           npm init -y


Step 2:  We need to install express js by following the command.

                 npm install express

Step 3: To reading data from excel we need exceljs.

npm install exceljs


const express = require("express");

var Excel = require("exceljs");

 

const app = express();

var wb = new Excel.Workbook();



Step 4: For reading data, go with the below mention code.


 

     app.get("/readxlxs", (req, res) => {

 

const dda = await wb.xlsx

    .readFile("./demo.xlsx")

    .then(async function () {

   

 var sh = wb.getWorksheet("Sheet1");

 

        for (let j = 1; j <= sh.rowCount; j++) {

           for (i = 2; i <= sh.columnCount; i++) {

             console.log("values == ",sh.getRow(j).getCell(i).value);

             }

          }

 });

    })

 


Step 5: For writing data to an excel file, go with the below mention code.

 

app.get("/writexlxs", (req, res) => {

 

const dda = await wb.xlsx

    .readFile("./demo.xlsx")

    .then(async function () {

   

 var sh = wb.getWorksheet("Sheet1");

  

  sh.getRow(2).getCell(1).value="Rohit"

 

    wb.xlsx.writeFile("demo.xlsx");

 });

 })

 


Step 6: Please mention the port number for running it on the local server.


const
port = process.env.PORT || 4000;

 

app.listen(port, () => {

 

 console.log(`Server is running on port ${port}.`);

 

});

 


Step 7: Hurray!!. Here is the output for reading the excel file. 



Hence, we have successfully read and write data from an excel file. 
Keep reading. All the Best :).





Comments

Post a Comment