hope
hope

Reputation: 23

How to use excel files with Nest JS

I am trying to creat a rest api which uses a third part api to get some status. I'll get the url from a excel file, for this specific case it needs to be a excel file, use them in my service to obtain the data from the third part api and save this response in the same excel file. I am already able to get the data from the third part api, but I'm failing to manage the excel through nest js. I tried to use exceljs library but it didn't work as I intended. I would like to have the return(assume it is inside a function) to be the cell value in this excel file. Could someone give me some hint in how to handle this file use inside nest js?

let Excel = require('exceljs');
    let workBook = new Excel.Workbook();
    workBook.xlsx.readFile('./ExcelFile/Archive.xlsx').then(function()
    {
        let sheet = workBook.getWorkSheet("Sheet1");
        let cellValue = sheet.getRow(2).getCell(1).value;
    });
    return cellValue;

Upvotes: 1

Views: 14959

Answers (1)

KibbeWater
KibbeWater

Reputation: 313

Since cellValue is defined inside a callback (.then(() => {}) you will need to return inside the callback.

Here however you you will face the issue that you cannot return it inside the callback. To fix this you have 2 options: Use async/await or return a promise

Async/await:

const Excel = require('exceljs');

async function ReadCell(filename) {
    let workBook = new Excel.Workbook();
    await workBook.xlsx.readFile(filename);

    let sheet = workBook.getWorkSheet('Sheet1');
    let cellValue = sheet.getRow(2).getCell(1).value;
    
    return cellValue;
}

Promises:

const Excel = require('exceljs');

async function ReadCell(filename) {
    return new Promise((resolve, reject) => {
        let workBook = new Excel.Workbook();
        workBook.xlsx.readFile(filename).then(() => {
            let sheet = workBook.getWorkSheet('Sheet1');
            let cellValue = sheet.getRow(2).getCell(1).value;
            resolve(cellValue);
        }).catch(err => /* Do some error handling here if you want to */ reject(err));
    });
}

Keep in mind that when using promises you are going to need to use .then((result) => {/* your code here */}) when trying to get the result of your ReadCell() function.

You can find more info about promises here

Upvotes: 2

Related Questions