将一列单元格从一个电子表格复制到另一个电子表格的最有效方法是什么?

时间:2018-11-09 09:51:37

标签: google-apps-script google-sheets

我正在尝试将一列单元格从电子表格复制到另一列(在底部添加)。下面的代码有效,但是我想知道是否有可能不进行循环。有没有更快或更有效的方法?

function CopyToAnotherSheet() {

  var sourceSpreadSheet = SpreadsheetApp.getActiveSpreadsheet();
  var srcSheet = sourceSpreadSheet.getSheets()[0];

  var destinationSpreadSheet = SpreadsheetApp.openById('15-vXNpnzSEKzcqhBmJ_D173rwGyM7TOAZE1iL_wsf2A');
  var destSheet = destinationSpreadSheet.getSheets()[0]; 

  // Get the contents of a cell in srcSheet
  var range = srcSheet.getRange("xposed!A1:A")
  var values = range.getValues();

  for (var i = 0; i < values.length; i++) {
      destSheet.appendRow(values[i]);
      }
}

干杯!

1 个答案:

答案 0 :(得分:1)

您可以将getRange()方法与setValues一起使用,以将setValues()设置为仅数组。 请参阅此文档以获取清晰的主意Document Link

function CopyToAnotherSheet() {

  var sourceSpreadSheet = SpreadsheetApp.getActiveSpreadsheet();
  var srcSheet = sourceSpreadSheet.getSheets()[0];

  var destinationSpreadSheet = SpreadsheetApp.openById('15-vXNpnzSEKzcqhBmJ_D173rwGyM7TOAZE1iL_wsf2A');
  var destSheet = destinationSpreadSheet.getSheets()[0]; 

  // Get the contents of a cell in srcSheet
  var range = srcSheet.getRange("xposed!A1:A")
  var values = range.getValues();

  //returns last row of the destination sheet
  var lastRow=destSheet.getLastRow();

  //starting from the last row, it will apend the array in the column
  //getrange(num of row to start from, num of column to start from, number of rows in array to append, num of column in array to append)
  destSheet.getRange(lastRow+1, 1, values.length,1).setValues(values);

}