Trying to read data from a Google Spreadsheet

时间:2018-04-18 17:49:33

标签: javascript google-apps-script

I've been trying to read data from a spreadsheet that returns a string based on whether or not the item is in stock or not. I just started this project and haven't compared it to the numeric values, but I'm already running into issues with reading the data and returning a string. Really new to Google script, don't know much about it - any advice would help! Thanks in advance.

function OrganizeData() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1");
  var data = ss.getDataRange().getValues();
  var message = "".toString();

  if (data[2].toString() == "Software" && data[3].toString() == "Garage Band") {
    return message = "Item is available!";

  } else if (data[2].toString() != "Software" && data[3].toString() == "Garage Band") {
    return message = "Current item is out of stock.";

  }
}

2 个答案:

答案 0 :(得分:0)

It looks like you are accessing the data set incorrectly. The .getValues() method you are calling returns a two-dimensional array of objects and you are only accessing the first dimension of that structure. Unless the concatenation of the entire row/column is the string you are looking for, the initial if statement will fail.

Hope this helps!

答案 1 :(得分:0)

使用以下示例数据:

| ID | Name | Type     | Category    | In Stock                      | 
|----|------|----------|-------------|-------------------------------| 
| 1  | Foo  | Software | Garage Band | Item is available!            | 
| 2  | Bar  | Food     | Garage Band | Current item is out of stock. | 

我能够在" In Stock"中添加消息。细胞

function showMessage(sheetName, targetCol) {
  var activeSpreadsheet = SpreadsheetApp.getActive();
  var sheet = activeSpreadsheet.getSheetByName(sheetName);
  var data = sheet.getDataRange().getValues();

  for (var row = 1; row < data.length; row++) {
    var productType = data[row][2].toString();
    var productName = data[row][3].toString();
    var message = '';

    if (productType === "Software" && productName === "Garage Band") {
      message = "Item is available!";

    } else if (productType !== "Software" && productName === "Garage Band") {
      message = "Current item is out of stock.";
    }

    sheet.getRange(row + 1, targetCol).setValue(message);
  }
}

function OrganizeData() {
  showMessage('Form Responses 1', 5);
}

// Select `OrganizeData` from drop-down and run program