Export to Excel in Node js

Leave a Comment

To export data in node js we will use exceljs module. So let's direct jump into the code. 

Let's first install this module using below command 

npm i exceljs

now create file name as exportToExcel.js and copy paste below code

const excel = require("exceljs");

function exportExcel() {
    let workbook = new excel.Workbook();
    let worksheet = workbook.addWorksheet("Straw Hat");

    let exportData = [];

    exportData.push({
        id: "1",
        name: "Monkey D. Luffy",
        designation: "Captain",
        description: "The Captain of the Straw Hat Pirates"
    }, {
        id: "2",
        name: "Roronoa zoro",
        designation: "Swordsmen",
        description: "The Swordsmen of the Straw Hat Pirates"
    }, {
        id: "3",
        name: "Vinsmoke Sanji",
        designation: "Cook",
        description: "The cook of the Straw Hat Pirates"
    })

    worksheet.columns = [
        { header: "Id", key: "id", width: 25 },
        { header: "Name", key: "name", width: 25 },
        { header: "Designation", key: "designation", width: 25 },
        { header: "Description", key: "description", width: 25 },
    ];

    worksheet.addRows(exportData);

    workbook.xlsx.writeFile('One_Piece.xlsx');

}

exportExcel()

It's simple code first we import excel js in our code, then let's create workbook variable and add worksheet as "Straw Hat". We can add multiple worksheet in one excel file for different different data.


After that let's create array of data which we want to export in excel. after that let's add the column in worksheet with mapping of data, header value as column name and id value as data key name which we have to map to that column name. 


worksheet.addRows() function takes array of data as parameter and create worksheet with data and finally we will use workbook write file function to create a file with excel file name parameter. 


When we run this file node exportToExcel.js then it will automatically create the One_Piece.xlsx in folder with above json data.







0 comments:

Post a Comment

Powered by Blogger.