是否可以将此列作为数组进行迭代(它会更有效率)?



经过大量研究和挖掘谷歌应用脚本上的微薄文档,这是我发现从谷歌工作表中迭代数据的唯一方法。有谁知道列是否可以转换为数组并更有效地迭代?下面的功能有效,但不是很快。


function Recon(){
var currentValue;
var countAdvice = 0;
var lastValue = null;
var lastLine;
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Transactions");
var rowCount = spreadsheet.getLastRow();
spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Dashboard")
spreadsheet.getRange('D1').setValue(rowCount);
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Transactions");

for(var i = rowCount; i>1; i--){

currentValue = spreadsheet.getRange('G'+i).getValue();

if( lastValue != null && currentValue == (lastValue*(-1))){
spreadsheet.getRange('M'+i).setValue('okay');
spreadsheet.getRange('K'+i).setValue(currentValue);
spreadsheet.getRange('L'+i).setValue(lastValue);

spreadsheet.getRange('M'+lastLine).setValue('okay');
countAdvice++;

}
lastValue = currentValue;
lastLine = i;
}
spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Dashboard")

spreadsheet.getRange('E1').setValue(countAdvice);

}

每次调用getRange((时,您都在进行HTTP调用,然后必须出去,获取数据,然后解析它。最佳做法是获取一次大型数据集中的数据,然后再写入一次。

代码中还有其他一些问题:

  • 变量电子表格正在更改其引用,一旦它是事务,那么它就是仪表板。而不是这样做,而是创建 2 个单独的变量,每个工作表引用一个。
  • 你的 for 循环是倒退的,这有什么原因吗?

有关如何进行 1 次获取调用和 1 次写入调用的方法,请参见下文。

var transSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Transactions");  
var allRows = transSheet.getDataRange().getValues();
var outputArray = [];
// run through each row
allRows.forEach( function(row) {
var currentValue = row[6]; // column
// if some condition applies
if( currentValue == "whatever" ){
// place values in certain columns in that particular row
outputArray.push( ["this goes into col K", "this into col L", "this goes into col M" ] )
} else {
// place empty values in those columns
outputArray.push( ["", "", "" ])
}
});
// now the output is ready to be inserted
var startInsertingAtThisColumn = 7; // G
var writeOutputToSheet = transSheet.getRange( 1, startInsertingAtThisColumn, outputArray.length, outputArray[0].length ).setValues( outputArray );

参考 - 获取数据范围

最新更新