1

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);
    });

1
  • What problem are you facing? Commented Feb 16, 2024 at 8:59

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

1 Comment

@Nwp _ Thanks for your accept , can you give me up vote too?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.