使用JavaScript从Google应用程序脚本表中检索特定单元格值

时间:2017-12-14 13:29:48

标签: javascript google-apps-script google-sheets

我试图从Google应用程序脚本表中检索特定值。我有一张存储信息的表格。我想基于行循环遍历该表,并检索匹配的所有值并满足给定的条件。

例如

if (row[4].toString().toLowerCase() == anotherRow[4]){

    //then display all rows which match that specific value

    // e.g:  
    row[4]. Display everything that matches anotherRow only;

}

这就是我无法显示所有符合该条件的行,目前我能够显示所有行[4],行[4]是列

2 个答案:

答案 0 :(得分:0)

此脚本将获取一系列数据并将其存储为数组数组。

function getMultipleValues(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Sheet1');
  // getRange exp. - 
  //sheet.getRange(first row, first column, last row, last column)

  // Get a grid of data 4 rows and two columns
  var range = sheet.getRange(1,1,4,2);
  var dataGrid = range.getValues()
  Logger.log(dataGrid)
  //[["Fruit","quantity"],["pears",1],["apples",1],["grapes",3]]


  //Get a column of data
  var range = sheet.getRange(1,1,4,1);
  var dataColumn = range.getValues()
  Logger.log(dataColumn)
  //[["Fruit"],["pears],["apples"],["grapes"]]

  //If the column length is unknown. Get everything.
  //Be sure to delete rows that are not needed in the sheet when using this.  
  var range = sheet.getRange("A1:A");
  var allOfColumnA = range.getValues()
  Logger.log(allOfColumnA)
  //[["Fruit"],["pears],["apples"],["grapes"],[],[],[],[]]

}

答案 1 :(得分:0)

以Supertopaz为基础'回答,看起来数组的过滤方法可以删除不符合条件的行。例如,给定一组这样的数据:

Source data for function

以下函数会将数据与您指定的条件匹配,并将匹配项写入第二个工作表。



function writeMatches() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss.getSheetByName('Sheet1');
  var sheet2 = ss.getSheetByName('Sheet2');
  var criteria = sheet1.getRange(1,2,1,1).getValue(); // returns a single value if the range is a single cell
  var arData = sheet1.getRange(4,1,5,2).getValues(); // returns a 2d array
  var arOutput = [];
  var rangeOutput;
  
  arOutput = arData.filter(function(row){
    return row[1].toLowerCase() === criteria
    /* The callback function iterates through the array.
       When this expression evaluates to true, the 
       element is included in the output array.
       The callback function can also supply an optional
       index argument, if you want to compare symmetric
       arrays.
    */
  });
  rangeOutput = sheet2.getRange(1,1,arOutput.length,arOutput[0].length);
  rangeOutput.setValues(arOutput);
}