Introduction to node-xlsx
node-xlsx
is a powerful library for handling Excel files in Node.js applications. Whether you need to parse, read, or write .xlsx files, node-xlsx
provides a straightforward API to achieve your goals. This article introduces node-xlsx
and provides dozens of useful API explanations with code snippets to help you get started.
Installation of node-xlsx
First, install the library using npm:
npm install node-xlsx
Loading an Excel File
To load an Excel file, use the following API:
const xlsx = require('node-xlsx').default;
const workSheets = xlsx.parse('path/to/file.xlsx');
console.log(workSheets);
Reading Sheet Data
To access sheet data, you can loop through the sheets:
workSheets.forEach(sheet => {
console.log(sheet.name);
console.log(sheet.data);
});
Creating a New Excel File
To create a new Excel file, you can define the data and write it to a file:
const data = [
["Name", "Age", "City"],
["John Doe", 30, "New York"],
["Jane Doe", 25, "Los Angeles"]
];
const buffer = xlsx.build([{ name: "Sheet 1", data: data }]);
require('fs').writeFileSync('output.xlsx', buffer);
Adding Sheets to an Excel File
You can add multiple sheets to an Excel file:
const sheets = [
{ name: "Sheet 1", data: [["A1", "B1"], ["A2", "B2"]] },
{ name: "Sheet 2", data: [["C1", "D1"], ["C2", "D2"]] }
];
const buffer = xlsx.build(sheets);
require('fs').writeFileSync('multiSheetOutput.xlsx', buffer);
Complete App Example
Below is a simple Node.js app that reads an Excel file, processes the data, and writes a new Excel file with updated information:
// Importing the library
const xlsx = require('node-xlsx').default;
const fs = require('fs');
// Reading the input file
const workSheets = xlsx.parse('input.xlsx');
const data = workSheets[0].data;
// Adding a new column with computed values
const processedData = data.map((row, index) => {
if (index === 0) {
row.push('Processed Value');
} else {
row.push(Math.random());
}
return row;
});
// Creating a new sheet with the processed data
const buffer = xlsx.build([{ name: 'Processed Data', data: processedData }]);
fs.writeFileSync('processed_output.xlsx', buffer);
console.log('Processing complete and file saved as processed_output.xlsx');
Conclusion
The node-xlsx
library is a versatile tool for developers working with Excel files in Node.js. With its easy-to-use APIs, you can quickly read, write, and manipulate Excel data. We hope the provided examples help you integrate node-xlsx
into your projects seamlessly.
Hash: a1a9ac13efba05fb59af12b231315a074329d4fe632ec88681376deca0a90c48