Writing data to an Excel file using Node.js
A guide on how to write data to an Excel file using Node.js, employing the ExcelJS library for efficient and effective Excel file manipulation.
In this article, we will explore how to write data into an Excel file using Node.js with the help of the ExcelJS library. This method provides a simple and efficient way to create and store data in a tabular format within Node.js applications.
// Import the ExcelJS library
const ExcelJS = require('exceljs');
// Create a new workbook
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('Information');
// Add column headers
worksheet.columns = [
{ header: 'Name', key: 'name', width: 20 },
{ header: 'Age', key: 'age', width: 10 },
{ header: 'City', key: 'city', width: 20 },
];
// Add data to the worksheet
worksheet.addRow({ name: 'Nguyen Van A', age: 23, city: 'Hanoi' });
worksheet.addRow({ name: 'Tran Thi B', age: 25, city: 'Ho Chi Minh' });
worksheet.addRow({ name: 'Le Van C', age: 21, city: 'Da Nang' });
// Save the workbook to an Excel file
workbook.xlsx.writeFile('output.xlsx')
.then(() => {
console.log('Data has been successfully written to the Excel file.');
})
.catch((error) => {
console.error('An error occurred while writing to the Excel file:', error);
});
Detailed Explanation
const ExcelJS = require('exceljs');
: Imports the ExcelJS library to use Excel-related functionalities.const workbook = new ExcelJS.Workbook();
: Creates a new workbook.const worksheet = workbook.addWorksheet('Information');
: Adds a new worksheet named "Information."worksheet.columns = [...]
: Sets up columns with corresponding headers and widths.worksheet.addRow(...)
: Adds rows of data to the worksheet.workbook.xlsx.writeFile('output.xlsx')
: Writes the data to an Excel file named "output.xlsx."console.log(...)
: Outputs a success or error message.
System Requirements
- Node.js v12 or later
- Library:
exceljs
How to install the libraries needed to run the Node.js code above
Use the following command to install:
npm install exceljs
Tips
- Make sure to install the ExcelJS library before running the code.
- For more complex Excel operations, refer to the ExcelJS documentation to leverage advanced features.