1

Can anyone assist me with loading an array with excel data and returning it as a function? This is my initial code:

var excel = require('exceljs');

var wb = new excel.Workbook();
var path = require('path');
var filePath = path.resolve(__dirname,'data.xlsx');

function signIn(){
    var SignIn = [];
    wb.xlsx.readFile(filePath).then(function(){
        var sh = wb.getWorksheet("Sheet1");
        for(var i = 1; i < 3; i++){
            SignIn.push(sh.getRow(i).getCell(2).value);
        }
    });
    return SignIn
}
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Orelsanpls Aug 23 '18 at 14:38
  • There is a lot to read through in that post but I do not see anything that solves my problem –  Aug 23 '18 at 14:50

1 Answers1

0

Workbook.readFile is aynchronous, you need to use either a callback or promise type approach. Using promises we can try:

var excel = require('exceljs');
var wb = new excel.Workbook();
var path = require('path');
var filePath = path.resolve(__dirname,'data.xlsx');

function signIn() {
    var SignIn = [];
    return wb.xlsx.readFile(filePath).then( () => {
        var sh = wb.getWorksheet("Sheet1");
        for(var i = 1; i < 3; i++){
            SignIn.push(sh.getRow(i).getCell(2).value);
        }
        return SignIn;
    });
}

async function testReadData() {
    try {
        let data = await signIn();
        console.log('testReadData: Loaded data: ', data);
    } catch (error) {
        console.error('testReadData: Error occurred: ', error);
    }
}
testReadData();

Or you can use a callback type approach:

function signInWithCallback(callback) {
    var SignIn = [];
    wb.xlsx.readFile(filePath).then(function(){
        var sh = wb.getWorksheet("Sheet1");
        for(var i = 1; i < 3; i++){
            SignIn.push(sh.getRow(i).getCell(2).value);
        }
        callback(SignIn);
    });
}

signInWithCallback((data) => console.log('Callback: Data: ', data));
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40