更快地将多个Google工作表合并为一个工作表

时间:2019-01-17 13:40:37

标签: google-apps-script google-sheets

我有一个Google表格,其中还有大约50-60个标签页。这些工作表中的所有数据都是相同的格式,我只需要合并到一个主电子表格中即可。我尝试了第二个答案here,但超时时间错误。这很慢,因为它粘贴了每一行-因此超过了时间限制。我正在尝试使用getValuessetValues函数来执行此操作,但是我在确定如何在lastRowlastColumn之后追加内容时遇到了问题。这是代码-

var ss = SpreadsheetApp.getActiveSpreadsheet();
var All = ss.insertSheet("MergedMasterSheet");
function TotalsSheet() {
   var sheets = ss.getSheets();
   for (var i=0; i < sheets.length; i++) 
    {
     var sheet = sheets[i];
     var range = sheet.getDataRange();
     var values = range.getValues();
     var lastrow = All.getLastRow();
     var lastcolumn = All.getLastColumn();
    // All.getRange().setValues(values) here is the problem with the 
    getRange() function
  } 
 }

1 个答案:

答案 0 :(得分:0)

您可以将所有数据写入一个数组,然后将该数组写入“ MergedMasterSheet”。看看是否可行:

function TotalsSheet() {
var ss, merged, array;
ss = SpreadsheetApp.getActiveSpreadsheet();
merged = ss.getSheetByName("MergedMasterSheet")

//create sheet if it doesn't exist, else clear all content
merged = !merged ? ss.insertSheet("MergedMasterSheet") : merged.clear();

//create a 2D-array containing all data of all sheets, except the sheet for the merged data
ss.getSheets().forEach(function (sh, i) {
    if(sh.getName() !== "MergedMasterSheet") {
    array = (i == 0) ? sh.getDataRange().getValues() : array.concat(sh.getDataRange().getValues())
    }
})

//filter out rows with no value in first column
array = array.filter(function (r) {
    return r[0];
})

//write everything to the merged sheet in one call
merged.getRange(1, 1, array.length, array[0].length).setValues(array)
}