繁体   English   中英

如何使用应用程序脚本遍历谷歌工作表中的每一行和每一列值?

[英]how to loop through each rows and column values in google sheet using app script?

在此处输入图像描述

我正在尝试使用应用程序脚本遍历谷歌表中的所有金额值,但是当我使用 for 循环时,我只能获得“aoumnt 1”列值,

  var sheetSource1 = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
for (var i = 1; i <= 3; i++) {
var activecell = sheetSource1.getRange(i + 2, 2).getValue();
Logger.log(activecell);
}

当我运行 Logger.log() 我得到如下

  • 860
  • 650
  • 420

但我想重新获得

  • 860
  • 650
  • 420
  • 760
  • 550
  • 525

如何达到这个结果。?

因此,当您使用getValue进行迭代时,您需要循环两次:

function myFunction() {
  var sheetSource1 = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  for (var i = 1; i <= 2; i++) {
    for (var j = 1; j <= 3; j++) {
      var activecell = sheetSource1.getRange(j + 3, i + 1).getValue();
      Logger.log(activecell);
    }
  }
}

但是嵌套for并不是最好的表现或实践。 然后,我们可以使用getValues()返回一个 arrays 数组(多维二维数组)。 并从那里迭代整个范围作为一个独特的来源:

function myFunctionT() {
  var data = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  let numCols = 2;
  let numRows = 3;
  var range = data.getRange(4, 2, numRows, numCols).getValues(); // <- using getValues(), and getRange can have multiple types of parameters to get ranges
  let col1 = [];
  let col2 = [];
  
  for (var i = 0; i < numRows; i++) {
    var row = range[i];
    var firstColValue = row[0];
    var secondColValue = row[1];
    col1.push(firstColValue);
    col2.push(secondColValue);
  }

  let list = [...col1, ...col2];
  Logger.log(list)

}

暂无
暂无

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

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