简体   繁体   English

尝试从Google Spreadsheet读取数据

[英]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! 对Google脚本来说真的很新,对它了解不多-任何建议都会有所帮助! 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. 您正在调用的.getValues()方法将返回一个二维对象数组,并且您仅访问该结构的第一维。 Unless the concatenation of the entire row/column is the string you are looking for, the initial if statement will fail. 除非整个行/列的连接是您要查找的字符串,否则初始if语句将失败。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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