简体   繁体   中英

Trying to read data from a Google Spreadsheet

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.";

  }
}

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!

With the following sample data:

| 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. | 

I was able to add the messages inside the "In Stock" cells.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM