To handle Excel files in Node.js, install the node-xlsx package using npm.
npm install node-xlsx
The node-xlsx library proivdes two primary functions: parse() for reading Excel files and build() for creating them. The parse() method accepts a file path and returns an array of objects representing the workbook's sheets.
To convert an Excel file into a JSON structure, the following code reads the first worksheet and maps the data rows to objects using the first row as proeprty names.
const xlsx = require('node-xlsx');
const fs = require('fs');
// Load and parse the spreadsheet file
const sheets = xlsx.parse('./origin.xlsx');
const firstSheetData = sheets[0].data;
// Extract column headers and data rows
const headers = firstSheetData[0];
const dataRows = firstSheetData.slice(1);
// Convert each row into an object
const jsonResult = dataRows.map(row => {
const rowObject = {};
row.forEach((cellValue, columnIndex) => {
rowObject[headers[columnIndex]] = cellValue;
});
return rowObject;
});
// Save the result as a JSON file
fs.writeFileSync('./output.json', JSON.stringify(jsonResult, null, 2));
console.log('Conversion completed successfully.');
Execute the script with Node.js to generate the output.json file containing the structured data.