Google Sheet Api get function returning undefined

2020-03-05 03:22发布

问题:

function changeData(auth,sheetId) {
  var sheets = google.sheets('v4');
  sheets.spreadsheets.values.update({
    auth: auth,
    spreadsheetId: sheetId,
    range: 'Sheet1!D6', 
    valueInputOption: "USER_ENTERED",
    resource: {
      values: [ ["abc"] ]
    }
  }, (err, response) => {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    } else {
        console.log("Appended");
    }
  });
}

I can get the above function to work and it changes the value just fine but the below function doesnt return value and says 0 rows retrieved. what am i doing wrong?

function read(auth,sheet_id)
    {
      var sheets = google.sheets('v4');
        sheets.spreadsheets.values.get({
        auth: auth,
        spreadsheetId: sheet_id,
        range: 'Sheet1!D6'
      }, function(err, result) {
        if(err) {
          // Handle error
          console.log(err);
        } else {
          var numRows = result.values ? result.values.length : 0;
          console.log('%d rows retrieved.', numRows);
        }
      });
    }

回答1:

If you are using googleapis after the version of v26.0.1 (now it's 32.0.0.), in your script, you can retrieve the data by result.data. So how about the following modification?

From :

var numRows = result.values ? result.values.length : 0;

To :

var numRows = result.data.values ? result.data.values.length : 0;