Node js выгрузка в excel

install exceljs

npm i exceljs --save

import exceljs

var Excel = require('exceljs');
var workbook = new Excel.Workbook();

create workbook

var options = {
                filename: __dirname+'/Reports/'+reportName,
                useStyles: true,
                useSharedStrings: true
            };

            var workbook = new Excel.stream.xlsx.WorkbookWriter(options);

after create worksheet

var worksheet = workbook.addWorksheet('Rate Sheet',{properties:{tabColor:{argb:'FFC0000'}}});

in worksheet.column array you pass column name in header and array key
pass in key

worksheet.columns = [
            { header: 'column name', key: 'array key', width: 35},
            { header: 'column name', key: 'array key', width: 35},
            { header: 'column name', key: 'array key', width: 20},

            ];

after using forEach loop append row one by one in exel file

array.forEach(function(row){ worksheet.addRow(row); })

you can also perfome loop on each exel row and cell

worksheet.eachRow(function(row, rowNumber) {
    console.log('Row ' + rowNumber + ' = ' + JSON.stringify(row.values));
});
row.eachCell(function(cell, colNumber) {
    console.log('Cell ' + colNumber + ' = ' + cell.value);
});

Cover image for How to save JSON data in EXCEL file using Node.js

In some scenarios, you have 3rd party API which returns data in JSON format and you need that data in excel file. How we can do this? Let’s follow me up for the next 5 minutes.

Today we are saving our JSON data in the EXCEL file using an excel4node library in node.js.

Let’s jump to the code and then I will explain code line by line.

Create index.js

Create package.json using

npm init

Install excel4node using

npm install —save excel4node

Define your data you want to be store in excel

    const data = [
      {
        "name":"Shadab Shaikh",
        "email":"shadab@gmail.com",
        "mobile":"1234567890"
      }
    ]

Import excel4node library

    const xl = require('excel4node');

Create a workbook and give some awesome name

    const wb = new xl.Workbook();
    const ws = wb.addWorksheet('Worksheet Name');

Now Let’s define columnName

    const headingColumnNames = [
        "Name",
        "Email",
        "Mobile",
    ]

Before moving to next let’s explore some functions in excel4node library

1. cell(rownumber,columnnumber)
requires 2 parameter
a. row number(starts from 1)
b. column number(starts from 1)
This function selects cell with given rowno and columnno

2. string(data) , number(data)
we can store data as string or number
just call the above functions and pass data in it.

Now write columnName in Excel file using functions in excel4node

    let headingColumnIndex = 1;
    headingColumnNames.forEach(heading => {
        ws.cell(1, headingColumnIndex++)
            .string(heading)
    });

Finally, Write our data in excel file

(Don’t forget to start row number from 2)

    let rowIndex = 2;
    data.forEach( record => {
        let columnIndex = 1;
        Object.keys(record ).forEach(columnName =>{
            ws.cell(rowIndex,columnIndex++)
                .string(record [columnName])
        });
        rowIndex++;
    });

Now Let’s take workbook and save it into the file

    wb.write('filename.xlsx');

Here is full code, just copy and paste in your favorite editor to go through demo.

const xl = require('excel4node');
const wb = new xl.Workbook();
const ws = wb.addWorksheet('Worksheet Name');

const data = [
 {
    "name":"Shadab Shaikh",
    "email":"shadab@gmail.com",
    "mobile":"1234567890"
 }
]

const headingColumnNames = [
    "Name",
    "Email",
    "Mobile",
]

//Write Column Title in Excel file
let headingColumnIndex = 1;
headingColumnNames.forEach(heading => {
    ws.cell(1, headingColumnIndex++)
        .string(heading)
});

//Write Data in Excel file
let rowIndex = 2;
data.forEach( record => {
    let columnIndex = 1;
    Object.keys(record ).forEach(columnName =>{
        ws.cell(rowIndex,columnIndex++)
            .string(record [columnName])
    });
    rowIndex++;
}); 
wb.write('TeacherData.xlsx');

When we have some reporting or admin panel application, we often need to download data in Excel. In this article, we will learn how to export data in excel using node js. There are different packages available in the market to export the data in node js. We will be using exceljs package to export data in an excel file.

ExcelJS is a data manipulation package available in node js to read manipulate and write data and styles to XLSX. ExcelJS is one of the best packages for data manipulation freely available and frequently updated from time to time.

Prerequisites

  1. A basic understanding of Node js

How to export data in excel using node js?

Project Setup

Create a directory named  node-export, and change it into that directory using the following command.

mkdir node-export
cd node-export

Inside the node-export directory, initialize a node js project using

npm init

After the command, a new package.json file will be created in the node-export folder.

export data in excel using node js

package.json

Now, let’s install the required dependencies required to export the data in an excel file.

npm install express exceljs

This will install express and exceljs modules which will be used for routing and exporting data to excel files respectively.

Next, let’s create a index.js file where we will create a route through which download will happen.

routes

The above code will initialize the express framework, set up the server at port 3000, and create a route downloadExcel which is used to export data to an excel file.

Create sample data for exporting

Let’s create a model file named user.js inside the Model folder which contains the sample data for exporting to the excel file. Typically, we will connect to relational or non-relational databases and get data. You can follow this article to learn how to add, delete and fetch data from the database in node js.

// Sample data
const User = [
  { 
   name: "John",
   email: "john@gmail.com", 
   gender: "Male" 
  },
  {
   name: "Harry",
   email: "harry@gmail.com",
   gender: "Male",
  },
  {
  name: "Olivia",
  email: "olivia@gmail.com",
  gender: "Female",
  },
  ];
  module.exports = User;

Export data to an excel file

In this step, let’s create a file where we will write a logic to store the sample data provided above to the excel file using the package exceljs. Let the name of the file be user.js which will be located inside Controller folder.

Now, let’s update our index.js file, so that when downloadExcel the route is called out controller logic will be called.

const express = require('express')
const exportUser = require('./Controller/user');

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.get("/downloadExcel", exportUser);

app.listen(3000, function () {
  console.log('App listening on port 3000!');
});

Finally, let’s write a logic to export the sample data into the excel file in our user.js file inside the Controller folder.

Controller/user.js

const User = require("../Models/user"); // This has data to be used
const excelJS = require("exceljs");

const exportUser = async (req, res) => {
  const workbook = new excelJS.Workbook();  // Create a new workbook
  const worksheet = workbook.addWorksheet("My Users"); // New Worksheet
  const path = "./files";  // Path to download excel

  // Column for data in excel. key must match data key
  worksheet.columns = [
    { header: "S no.", key: "s_no", width: 10 },
    { header: "Name", key: "name", width: 10 },
    { header: "Email Id", key: "email", width: 10 },
    { header: "Gender", key: "gender", width: 10 },
  ];

  // Looping through User data
  let counter = 1;
  User.forEach((user) => {
    user.s_no = counter;
    worksheet.addRow(user); // Add data in worksheet
    counter++;
  });

  // Making first line in excel bold
  worksheet.getRow(1).eachCell((cell) => {
    cell.font = { bold: true };
  });

  try {
    const data = await workbook.xlsx.writeFile(`${path}/users.xlsx`)
      .then(() => {
        res.send({
          status: "success",
          message: "file successfully downloaded",
          path: `${path}/users.xlsx`,
        });
      });
  } catch (err) {
    console.log(err);
    res.send({
      status: "error",
      message: err,
    });
  }
};

module.exports = exportUser;

Here, we create an exceljs workbook object inside which we create a worksheet named My Users. In this object, we can create multiple worksheets but for this, we have only created a single sheet that will contain exported data. After that, we create a column to be displayed in the excel file. While defining the worksheet column, the key index should match with the data key returned from the Model/user.js file.

After, creating the columns we have looped through the model data and add it to the worksheet. Then, we modify the heading of the excel file so that we can distinguish between data and heading. This command cell.font = { bold: true } is used to make the heading bold. Then, the following command will export the model data into an excel file.

await workbook.xlsx.writeFile(`${path}/users.xlsx`)

The exported excel file will be stored in the files/users.xlsx location. The exported file will look like the following:

Conclusion

By following the above process, we can export data in excel file in node js using the exceljs package. If you are searching for exporting files in other languages like Laravel you can follow this link.

There may be times when you need to generate an Excel file from your Node.js application. You may need to get data from a database or a web service, then output it to an Excel file for further reporting or analysis. SpreadJS makes this possible without any Excel requirements on the server.

Node.js is a popular event-driven JavaScript runtime that is typically used in creating network applications. It can handle multiple connections simultaneously and doesn’t depend on threads like most other models.

In this tutorial, learn how to use SpreadJS to gather information entered by the user and automatically export it to an Excel file—all in your Node.js application.

  1. Get Started with SpreadJS and Node.js
  2. Use the SpreadJS npm Package
  3. Read an Excel File In Your Node.js Application
  4. Gather User Input
  5. Fill Out Your Excel File
  6. Export Node.js Out to Excel

With the power of SpreadJS, performance is not affected whether using SpreadJS by itself or with Node.js.

Download the sample zip for this project.

Ready to get Started? Download SpreadJS Today!

Import/Export XLSX Node.js

Get Started with SpreadJS Spreadsheets and Node.js

To start, we’ll need to install Node.js and the Mock-Browser, BufferJS, and FileReader, each of which can be found at these links:

Installing Node.js via Package Manager

Mock-Browser

BufferJS

FileReader

While you can use most IDE to create this application, we’ll use Visual Studio 2019 in this blog. Once Visual Studio is open, create a new application using Create a new project, and then search for «Blank Node.js Console Application«. Please give it a name and specify a location to create the project.

This will automatically create the required files and open up the “app.js” file, which is the only file we’ll be changing.

To install the packages in the project, right-click the «npm» header in the Solution Explorer, click Install New npm Packages and search and install each package for «Mock-Browser», «BufferJS», and «FileReader».

Once you have that installed, the dependencies should update in the package.json file:

{
  "name": "spread-jsnode-js",
  "version": "0.0.1",
  "description": "SpreadJSNodeJS",
  "main": "app.js",
  "author": {
    "name": ""
  },
  "dependencies": {
    "@grapecity/spread-excelio": "^16.0.4",
    "@grapecity/spread-sheets": "^16.0.4",
    "bufferjs": "^3.0.1",   
    "filereader": "^0.10.3",
    "mock-browser": "^0.92.14"
  }
}

In this sample, we’ll use the File System Module of Node.js. We can load that in:

var fs = require('fs');

To use SpreadJS with Node.js, we can load the Mock-Browser that we installed:

var mockBrowser = require('mock-browser').mocks.MockBrowser;

Before loading the SpreadJS script, we’ll need to initialize the mock-browser. Initialize the variables that we may need to use later in the application, particularly the «window» variable:

global.window = mockBrowser.createWindow();
global.document = window.document;
global.navigator = window.navigator;
global.HTMLCollection = window.HTMLCollection;
global.getComputedStyle = window.getComputedStyle;

Initialize the FileReader library:

var fileReader = require('filereader');
global.FileReader = fileReader;

Use the SpreadJS npm Package

The SpreadJS and ExcelIO packages will need to be added to the project. You can add these to your project by right-clicking the «npm» section of the Solution Explorer and selecting Install New npm Packages. You should be able to search for «GrapeCity» and install the following two packages:

@grapecity/spread-sheets

@grapectiy/spread-excelio

Once the SpreadJS npm packages have been added to the project, the package.json should be automatically uploaded with the correct dependencies:

{
  "name": "spread-jsnode-js",
  "version": "0.0.1",
  "description": "SpreadJSNodeJS",
  "main": "app.js",
  "author": {
    "name": ""
  },
  "dependencies": {
    "@grapecity/spread-excelio": "^16.0.4",
    "@grapecity/spread-sheets": "^16.0.4",
    "bufferjs": "^3.0.1",
    "filereader": "^0.10.3",
    "mock-browser": "^0.92.14"
  }
}

Now we’ll need to require that in the app.js file:

var GC = require('@grapecity/spread-sheets');
var SJSExcel = require('@grapecity/spread-excelio');

When using the npm package, the license key also needs to be set for both:

GC.Spread.Sheets.LicenseKey = "<YOUR KEY HERE>";
SJSExcel.LicenseKey = "<YOUR KEY HERE>";

In this particular application, we’ll show the user which version of SpreadJS they are using. To do this, we can require the package.json file and then reference the dependency to get the version number:

var packageJson = require('./package.json');
console.log('n** Using SpreadJS Version "' + packageJson.dependencies["@grapecity/spread-sheets"] + '" **');

Read the Excel File Into Your Node.js Application

We’ll read in an existing Excel template file, getting data from the user. Next, place the data into the file and export it. In this case, the file is an invoice that the user can edit.

Start by initializing the workbook and Excel IO variables, as well as the variables for the sheet index:

var wb = new GC.Spread.Sheets.Workbook();

var billingInvoiceSheetIndex = 1;
var companySetupSheetIndex = 2;

var excelIO = new SJSExcel.IO();

Let’s wrap our code in a try/catch block as we read in the file. Then we can initialize the variable “readline” – which is essentially a library that allows you to read data that the user inputs into the console. Next, we’ll store it into a JavaScript array that we can use to fill out the Excel file easily:

// Instantiate the spreadsheet and modify it
console.log('nManipulating Spreadsheetn---');
try {
    var file = fs.readFileSync('./content/billingInvoiceTemplate.xlsx');
    excelIO.open(file.buffer, (data) => {
        wb.fromJSON(data);
        const readline = require('readline');

        var invoice = {
            generalInfo: [],
            invoiceItems: [],
            companyDetails: []
        };
    });
} catch (e) {
    console.error("** Error manipulating spreadsheet **");
    console.error(e);
}

Gather User Input

Import/Export Excel Node.js

The above image shows the Excel file we are using. The first information we want to gather is the general invoice information. We can make a separate function within the excelio.open call to prompt the user in the console for each item that we’ll need.

We can create a separate array to save the data to after each input, then when we have all of the input for that section. Push it to the invoice.generalInfo array that we created:

function fillGeneralInformation() {
    console.log("-----------------------nFill in Invoice Detailsn-----------------------")
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    var generalInfoArray = [];
    rl.question('Invoice Number: ', (answer) => {
        generalInfoArray.push(answer);
        rl.question('Invoice Date (dd Month Year): ', (answer) => {
            generalInfoArray.push(answer);
            rl.question('Payment Due Date (dd Month Year): ', (answer) => {
                generalInfoArray.push(answer);
                rl.question('Customer Name: ', (answer) => {
                    generalInfoArray.push(answer);
                    rl.question('Customer Company Name: ', (answer) => {
                        generalInfoArray.push(answer);
                        rl.question('Customer Street Address: ', (answer) => {
                            generalInfoArray.push(answer);
                            rl.question('Customer City, State, Zip (<City>, <State Abbr> <Zip>): ', (answer) => {
                                generalInfoArray.push(answer);
                                rl.question('Invoice Company Name: ', (answer) => {
                                    generalInfoArray.push(answer);
                                    rl.question('Invoice Street Address: ', (answer) => {
                                        generalInfoArray.push(answer);
                                        rl.question('Invoice City, State, Zip (<City>, <State Abbr> <Zip>): ', (answer) => {
                                            generalInfoArray.push(answer);
                                            rl.close();

                                            invoice.generalInfo.push({
                                                "invoiceNumber": generalInfoArray[0],
                                                "invoiceDate": generalInfoArray[1],
                                                "paymentDueDate": generalInfoArray[2],
                                                "customerName": generalInfoArray[3],
                                                "customerCompanyName": generalInfoArray[4],
                                                "customerStreetAddress": generalInfoArray[5],
                                                "customerCityStateZip": generalInfoArray[6],
                                                "invoiceCompanyName": generalInfoArray[7],
                                                "invoiceStreetAddress": generalInfoArray[8],
                                                "invoiceCityStateZip": generalInfoArray[9],
                                            });
                                            console.log("General Invoice Information Stored");
                                            fillCompanyDetails();
                                        });
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });
    });
}

Within that function, we call «fillCompanyDetails,» we’ll gather information about the company to fill into the second sheet of the workbook. The function will be very similar to the previous function:

function fillCompanyDetails() {
    console.log("-----------------------nFill in Company Detailsn-----------------------");
    const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
    var companyDetailsArray = []
    rl.question('Your Name: ', (answer) => {
        companyDetailsArray.push(answer);
        rl.question('Company Name: ', (answer) => {
            companyDetailsArray.push(answer);
            rl.question('Address Line 1: ', (answer) => {
                companyDetailsArray.push(answer);
                rl.question('Address Line 2: ', (answer) => {
                    companyDetailsArray.push(answer);
                    rl.question('Address Line 3: ', (answer) => {
                        companyDetailsArray.push(answer);
                        rl.question('Address Line 4: ', (answer) => {
                            companyDetailsArray.push(answer);
                            rl.question('Address Line 5: ', (answer) => {
                                companyDetailsArray.push(answer);
                                rl.question('Phone: ', (answer) => {
                                    companyDetailsArray.push(answer);
                                    rl.question('Facsimile: ', (answer) => {
                                        companyDetailsArray.push(answer);
                                        rl.question('Website: ', (answer) => {
                                            companyDetailsArray.push(answer);
                                            rl.question('Email: ', (answer) => {
                                                companyDetailsArray.push(answer);
                                                rl.question('Currency Abbreviation: ', (answer) => {
                                                    companyDetailsArray.push(answer);
                                                    rl.question('Beneficiary: ', (answer) => {
                                                        companyDetailsArray.push(answer);
                                                        rl.question('Bank: ', (answer) => {
                                                            companyDetailsArray.push(answer);
                                                            rl.question('Bank Address: ', (answer) => {
                                                                companyDetailsArray.push(answer);
                                                                rl.question('Account Number: ', (answer) => {
                                                                    companyDetailsArray.push(answer);
                                                                    rl.question('Routing Number: ', (answer) => {
                                                                        companyDetailsArray.push(answer);
                                                                        rl.question('Make Checks Payable To: ', (answer) => {
                                                                            companyDetailsArray.push(answer); rl.close();
                                                                            invoice.companyDetails.push({ "yourName": companyDetailsArray[0], "companyName": companyDetailsArray[1], "addressLine1": companyDetailsArray[2], "addressLine2": companyDetailsArray[3], "addressLine3": companyDetailsArray[4], "addressLine4": companyDetailsArray[5], "addressLine5": companyDetailsArray[6], "phone": companyDetailsArray[7], "facsimile": companyDetailsArray[8], "website": companyDetailsArray[9], "email": companyDetailsArray[10], "currencyAbbreviation": companyDetailsArray[11], "beneficiary": companyDetailsArray[12], "bank": companyDetailsArray[13], "bankAddress": companyDetailsArray[14], "accountNumber": companyDetailsArray[15], "routingNumber": companyDetailsArray[16], "payableTo": companyDetailsArray[17] });
                                                                            console.log("Invoice Company Information Stored");
                                                                            console.log("-----------------------nFill in Invoice Itemsn-----------------------");
                                                                            fillInvoiceItemsInformation();
                                                                        });
                                                                    });
                                                                });
                                                            });
                                                        });
                                                    });
                                                });
                                            });
                                        });
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });
    });
}

Now that we have the basic information for the invoice, we can focus on gathering the individual invoice items, which we’ll do in another function called «fillInvoiceItemsInformation.» Before each item, we’ll ask the user if they would like to add an item. If they keep entering «y», then we’ll gather that item’s information, then ask again until they type «n»:

function fillInvoiceItemsInformation() {
    const rl = readline.createInterface({
        input: process.stdin, output: process.stdout
    });
    var invoiceItemArray = [];
    rl.question('Add item?(y/n): ', (answer) => {
        switch (answer) {
            case "y": console.log("-----------------------nEnter Item Informationn-----------------------");
                rl.question('Quantity: ', (answer) => {
                    invoiceItemArray.push(answer);
                    rl.question('Details: ', (answer) => {
                        invoiceItemArray.push(answer);
                        rl.question('Unit Price: ', (answer) => {
                            invoiceItemArray.push(answer);
                            invoice.invoiceItems.push({
                                "quantity": invoiceItemArray[0], "details": invoiceItemArray[1], "unitPrice": invoiceItemArray[2]
                            });
                            console.log("Item Information Added");
                            rl.close();
                            fillInvoiceItemsInformation();
                        });
                    });
                });
                break;
            case "n": rl.close();
                return fillExcelFile();
                break;
            default: console.log("Incorrect option, Please enter 'y' or 'n'.");
        }
    });
}

Add Data to the Excel Spreadsheet

After gathering all the required invoice information, we can fill out the Excel file. For the billing information and company setup, we can manually set each value in the cell from the JavaScript array:

function fillExcelFile() {
    console.log("-----------------------nFilling in Excel filen-----------------------");
    fillBillingInfo();
    fillCompanySetup();
}

function fillBillingInfo() {
    var sheet = wb.getSheet(billingInvoiceSheetIndex);
    sheet.getCell(0, 2).value(invoice.generalInfo[0].invoiceNumber);
    sheet.getCell(1, 1).value(invoice.generalInfo[0].invoiceDate);
    sheet.getCell(2, 2).value(invoice.generalInfo[0].paymentDueDate);
    sheet.getCell(3, 1).value(invoice.generalInfo[0].customerName);
    sheet.getCell(4, 1).value(invoice.generalInfo[0].customerCompanyName);
    sheet.getCell(5, 1).value(invoice.generalInfo[0].customerStreetAddress);
    sheet.getCell(6, 1).value(invoice.generalInfo[0].customerCityStateZip);
    sheet.getCell(3, 3).value(invoice.generalInfo[0].invoiceCompanyName);
    sheet.getCell(4, 3).value(invoice.generalInfo[0].invoiceStreetAddress);
    sheet.getCell(5, 3).value(invoice.generalInfo[0].invoiceCityStateZip);
}

function fillCompanySetup() {
    var sheet = wb.getSheet(companySetupSheetIndex);
    sheet.getCell(2, 2).value(invoice.companyDetails[0].yourName);
    sheet.getCell(3, 2).value(invoice.companyDetails[0].companyName);
    sheet.getCell(4, 2).value(invoice.companyDetails[0].addressLine1);
    sheet.getCell(5, 2).value(invoice.companyDetails[0].addressLine2);
    sheet.getCell(6, 2).value(invoice.companyDetails[0].addressLine3);
    sheet.getCell(7, 2).value(invoice.companyDetails[0].addressLine4);
    sheet.getCell(8, 2).value(invoice.companyDetails[0].addressLine5);
    sheet.getCell(9, 2).value(invoice.companyDetails[0].phone);
    sheet.getCell(10, 2).value(invoice.companyDetails[0].facsimile);
    sheet.getCell(11, 2).value(invoice.companyDetails[0].website);
    sheet.getCell(12, 2).value(invoice.companyDetails[0].email);
    sheet.getCell(13, 2).value(invoice.companyDetails[0].currencyAbbreviation);
    sheet.getCell(14, 2).value(invoice.companyDetails[0].beneficiary);
    sheet.getCell(15, 2).value(invoice.companyDetails[0].bank);
    sheet.getCell(16, 2).value(invoice.companyDetails[0].bankAddress);
    sheet.getCell(17, 2).value(invoice.companyDetails[0].accountNumber);
    sheet.getCell(18, 2).value(invoice.companyDetails[0].routingNumber);
    sheet.getCell(19, 2).value(invoice.companyDetails[0].payableTo);
}

The template we are using has a specific number of rows laid out for the items in the invoice. The user may add more than the max. In this case, we can simply add more rows to the sheet. We’ll add the rows before setting the items in the sheet from the array:

function fillInvoiceItems() {
    var sheet = wb.getSheet(billingInvoiceSheetIndex);
    var rowsToAdd = 0;
    if (invoice.invoiceItems.length > 15) {
        rowsToAdd = invoice.invoiceItems.length - 15;
        sheet.addRows(22, rowsToAdd);
    }
    var rowIndex = 8;
    if (invoice.invoiceItems.length >= 1) {
        for (var i = 0; i < invoice.invoiceItems.length; i++) {
            sheet.getCell(rowIndex, 1).value(invoice.invoiceItems[i].quantity);
            sheet.getCell(rowIndex, 2).value(invoice.invoiceItems[i].details);
            sheet.getCell(rowIndex, 3).value(invoice.invoiceItems[i].unitPrice);
            rowIndex++;
        }
    }
}

Export Node.js Out to an Excel XLSX Spreadsheet

After the information has been filled out in the workbook, we can export the workbook to an Excel file. To do this, we’ll use the excelio open function. In this case, just put the date in the filename:

function exportExcelFile() {
    excelIO.save(wb.toJSON(), (data) => {
        fs.appendFileSync('Invoice' + new Date().valueOf() + '.xlsx', new Buffer(data), function (err) {
            console.log(err);
        });
        console.log("Export success");
    }, (err) => {
        console.log(err);
    }, { useArrayBuffer: true });
}

You can export your workbook to an Excel file with the above code snippet. Your completed file will look like this:

Import/Export Excel Node.js

Utilizing SpreadJS in conjunction with Node.js demonstrates another example of the versatility and extensibility of SpreadJS! Check out our blog page for more articles like this, demos, videos, and tutorials.

If you have any questions, feedback, or demo requests, please comment below!

Ready to get Started? Download SpreadJS Today!

  • Eric Cabrel TIOGO

Write data in an Excel file using Node.js and Typescript

Photo by Mika Baumeister / Unsplash

Photo by Mika Baumeister / Unsplash

Excel files are increasingly used to export data from a Web application to share with other applications or just for reporting and business decision-making. In Node.js, you can export data as PDF or CSV, but Excel can also be the preferred output format. We will see how to write data in an Excel file in this post.

If you are interested in how to generate a CSV file with Node.js, check out this article:

Generate a CSV file from data using Node.js

In this post, we will see how to write data coming from a database in a CSV file using Node.js and Typescript. We will a package called csv-writer.

Teco TutorialsEric Cabrel TIOGO

Set up the project

Make sure you have Node.js installed on your computer before continuing. I prepared a project starter to quickly start a Node.js project with Typescript. Let’s clone it and make it works locally.

git clone https://github.com/tericcabrel/node-ts-starter node-excel-write

cd node-excel-write

yarn install # or npm install

yarn start # or npm run start

Set up the project locally.

Set up the project locally.

Define the data to write

Let’s say we retrieve a list of countries from the database, and we want to write them in an Excel file. The first is to define the sample of data we want to write.

Replace the content of the file src/index.ts with the code below:

type Country = {
  name: string;
  countryCode: string;
  capital: string;
  phoneIndicator: number;
};

const countries: Country[] = [
  { name: 'Cameroon', capital: 'Yaounde', countryCode: 'CM', phoneIndicator: 237 },
  { name: 'France', capital: 'Paris', countryCode: 'FR', phoneIndicator: 33 },
  { name: 'United States', capital: 'Washington, D.C.', countryCode: 'US', phoneIndicator: 1 },
  { name: 'India', capital: 'New Delhi', countryCode: 'IN', phoneIndicator: 91 },
  { name: 'Brazil', capital: 'Brasília', countryCode: 'BR', phoneIndicator: 55 },
  { name: 'Japan', capital: 'Tokyo', countryCode: 'JP', phoneIndicator: 81 },
  { name: 'Australia', capital: 'Canberra', countryCode: 'AUS', phoneIndicator: 61 },
  { name: 'Nigeria', capital: 'Abuja', countryCode: 'NG', phoneIndicator: 234 },
  { name: 'Germany', capital: 'Berlin', countryCode: 'DE', phoneIndicator: 49 },
];

Note: I get the information about countries here: https://restcountries.com

Install the package ExcelJS

ExcelJS is an excellent library for manipulating an Excel file from Node.js. We will use it in this post, so let’s install it:

npm install exceljs

Create a sheet

With Excel, you can create many sheets where everything sheet contains different kinds of data.

The first to do with ExcelJS is to create the sheet that will hold the countries list. In the file, index.ts add the code below:

import Excel from 'exceljs';

const workbook = new Excel.Workbook();
const worksheet = workbook.addWorksheet('Countries List');

You can use as many sheets as you want; just give a proper variable name for each sheet.

const worksheetCountries = workbook.addWorksheet('Countries List');
const worksheetContinents = workbook.addWorksheet('Continents List');
const worksheetCities = workbook.addWorksheet('Cities List');

For this post, we only need one sheet.

Define the columns’ header

To create the table header, we need to map each column of the header to a property of the Country object.

Update the file src/index.ts, to add the code below:

const countriesColumns = [
  { key: 'name', header: 'Name' },
  { key: 'countryCode', header: 'Country Code' },
  { key: 'capital', header: 'Capital' },
  { key: 'phoneIndicator', header: 'International Direct Dialling' },
];

worksheet.columns = countriesColumns;

The value of the property  key must be a key of the object Country (name, countryCode, capital and phoneIndicator).
The property header can be anything, and it will be displayed as the header in the CSV file.

Write the data to the file

It is straightforward to write the file in the sheet.

countries.forEach((country) => {
  worksheet.addRow(country);
});

That’s it.

The remaining part is to generate the Excel file by providing the path to write the file. The code below does that:


import * as path from 'path';

const exportPath = path.resolve(__dirname, 'countries.xlsx');

await workbook.xlsx.writeFile(exportPath);

If you work with Excel and want to level up your skill, I recommend the guide below, containing 36 tutorials covering Excel basics, functions, and advanced formulas.

36 Excel Tutorials To Help You Master Spreadsheets — Digital.com

Excel spreadsheets are essentially databases. Here are 36 Excel tutorials you can use to master Excel and help your career or business grow.

Digital.comAkshat Biyani

Wrap up

Here is what the index.ts the file looks like this:

import Excel from 'exceljs';
import path from 'path';

type Country = {
  name: string;
  countryCode: string;
  capital: string;
  phoneIndicator: number;
};

const countries: Country[] = [
  { name: 'Cameroon', capital: 'Yaounde', countryCode: 'CM', phoneIndicator: 237 },
  { name: 'France', capital: 'Paris', countryCode: 'FR', phoneIndicator: 33 },
  { name: 'United States', capital: 'Washington, D.C.', countryCode: 'US', phoneIndicator: 1 },
  { name: 'India', capital: 'New Delhi', countryCode: 'IN', phoneIndicator: 91 },
  { name: 'Brazil', capital: 'Brasília', countryCode: 'BR', phoneIndicator: 55 },
  { name: 'Japan', capital: 'Tokyo', countryCode: 'JP', phoneIndicator: 81 },
  { name: 'Australia', capital: 'Canberra', countryCode: 'AUS', phoneIndicator: 61 },
  { name: 'Nigeria', capital: 'Abuja', countryCode: 'NG', phoneIndicator: 234 },
  { name: 'Germany', capital: 'Berlin', countryCode: 'DE', phoneIndicator: 49 },
];

const exportCountriesFile = async () => {
  const workbook = new Excel.Workbook();
  const worksheet = workbook.addWorksheet('Countries List');

  worksheet.columns = [
    { key: 'name', header: 'Name' },
    { key: 'countryCode', header: 'Country Code' },
    { key: 'capital', header: 'Capital' },
    { key: 'phoneIndicator', header: 'International Direct Dialling' },
  ];

  countries.forEach((item) => {
    worksheet.addRow(item);
  });

  const exportPath = path.resolve(__dirname, 'countries.xlsx');

  await workbook.xlsx.writeFile(exportPath);
};

exportCountriesFile();

Execute the file with the command: yarn start.

A file named countries.xlsx will be generated in the same folder containing the file index.ts. Open the file with an Excel file visualizer.

The excel file generated successfully.

The Excel file was generated successfully.

Yeah! it works

Styling the sheet

There is no distinction between the header and other rows on the spreadsheet, and the text’s header overlaps the column width.

We can apply styling on the header to customize the text and increase the column width.

Update the index.ts file with the code below:

worksheet.columns.forEach((sheetColumn) => {
    sheetColumn.font = {
      size: 12,
    };
    sheetColumn.width = 30;
});

worksheet.getRow(1).font = {
    bold: true,
    size: 13,
};

The forEach() on the worksheet columns will apply the styling, so we first want the font size for all the columns to be 12px and the column width to be 30px.

We want to make the header’s text bold and increase the font size to 13px. We know it is the first line of the sheet. Yeah, the index doesn’t start at 0 but at 1 ?.

Rerun the code to generate a new file, open the generated file again, and tadaaa!

The Excel file generated with a custom style.

The Excel file is generated with a custom style.

Wrap up

ExcelJS helps you with creating Excel file and writing data inside, but it also allows styling the spreadsheet columns. The support for TypeScript makes the experience of working with great.

Check out the package documentation to learn about other options.

You can find the code source on the GitHub repository.

Follow me on Twitter or subscribe to my newsletter to avoid missing the upcoming posts and the tips and tricks I occasionally share.

Like this post? Please share to your friends:
  • Node js word template
  • Node js import syntaxerror unexpected reserved word
  • Node js excel parser
  • No word for fun in russian
  • Node js excel import