Search code examples
javascriptnode.jsxlsx

Node.js Function returning undefined?


Trying to find a value in an excel file using the XLSX library:

The function works, it finds the value, however the output is undefined, even though the debugging say the value is found.

Here's the function:

var getValsFromExcel = function(sheet,idcol, valcol, val){
  var workbook = new Excel.Workbook(); 
  workbook.xlsx.readFile(__dirname + '/assets/gu.xlsx')
      .then(function() {
          var worksheet = workbook.getWorksheet(sheet);
          worksheet.eachRow({ includeEmpty: false }, function(row, rowNumber) {
            console.log("Row " + rowNumber + " = " + JSON.stringify(row.values));
            console.log(row.values[idcol]);
            console.log('checking ' + row.values[idcol] + ' = ' + val + ' ' + (row.values[idcol] == val))
            if (row.values[idcol] == val){
              console.log('Value found! its ' + row.values[valcol])
              //getValsFromExcel = row.values[valcol];
              return row.values[valcol];
            }
          });
      });
    }  

  var ans = getValsFromExcel('yesno',3, 4, tobj["respondent_consent"]);
  console.log('Q1 answer = ' + ans);

Here's the console output:

Q1 answer = undefined
Row 1 = [null,"UID","Delete(Y/N)","field: yesno_key_value","field: yesno_display_text"]
field: yesno_key_value
checking field: yesno_key_value = yes false
Row 2 = [null,"5b45fe42f7fe481d8442d5e94b894b45","N","yes","Si"]
yes
checking yes = yes true
Value found! its Si
Row 3 = [null,"b65ba5a1a3814a87b4571e8d477307aa","N","no","No"]
no
checking no = yes false

Solution

  • getValsFromExcel asynchronous, here is the correction:

    var getValsFromExcel = function(sheet,idcol, valcol, val){
      var workbook = new Excel.Workbook(); 
      return workbook.xlsx.readFile(__dirname + '/assets/gu.xlsx')
      .then(function() {
          var worksheet = workbook.getWorksheet(sheet);
          let answer = null;
          worksheet.eachRow({ includeEmpty: false }, function(row, rowNumber) {
            console.log("Row " + rowNumber + " = " + JSON.stringify(row.values));
            console.log(row.values[idcol]);
            console.log('checking ' + row.values[idcol] + ' = ' + val + ' ' + (row.values[idcol] == val))
            if (row.values[idcol] == val){
              console.log('Value found! its ' + row.values[valcol])
              //getValsFromExcel = row.values[valcol];
              answ = row.values[valcol];
              return;
            }
          });
          return answer;
      });
    }  
    
    getValsFromExcel('yesno',3, 4, tobj["respondent_consent"])
    .then( answer => console.log('Q1 answer = ' + ans) );