node.jsfeathersjsexceljs

how to read data from .xlsx file with exceljs


I am sending a .xlsx file through body form-data with key=excel, type=file, and value=text.xlsx. I want to read the values obtained from the excel file.

async create(data, params) {
    console.log(data);
    const { file } = data; // Assuming the file is sent as 'file' in form-data
    const workbook = new ExcelJS.Workbook();
    
    console.log(file);
    console.log(data);

    await workbook.xlsx.load(file.data); // Load the Excel file from binary data
    const worksheet = workbook.worksheets[0]; // Select the first worksheet
    
    const rows = [];
    worksheet.eachRow((row, rowNumber) => {
      const rowData = {};
      row.eachCell((cell, colNumber) => {
        rowData[`col${colNumber}`] = cell.value;
      });
      rows.push(rowData);
    });


Solution

  • This demo code will work

    Save as demo.js

    const fs = require('fs');
    const ExcelJS = require('exceljs');
    
    async function create(data, params) {
        const { file } = data;
        const workbook = new ExcelJS.Workbook();
        
        await workbook.xlsx.load(file.data);
        const worksheet = workbook.worksheets[0];
        
        const rows = [];
        worksheet.eachRow((row, rowNumber) => {
            const rowData = {};
            row.eachCell((cell, colNumber) => {
                rowData[`col${colNumber}`] = cell.value;
            });
            rows.push(rowData);
        });
    
        return rows;
    }
    
    async function processDataFile() {
        try {
            // Read the data.xlsx file
            const fileData = fs.readFileSync('data.xlsx');
    
            const data = {
                file: {
                    data: fileData
                }
            };
    
            const params = {};
    
            const rows = await create(data, params);
    
            console.log('Data read successfully:', rows);
        } catch (error) {
            console.error('Error processing data file:', error);
        }
    }
    
    processDataFile();
    

    Input data

    Save as data.xlsx

    enter image description here

    Install dependencies

    npm install fs exceljs
    

    Run it

    node demo.js
    

    Result

    enter image description here