Google Script要从文件夹中的每个工作表复制到基于文件夹的主工作表吗?

时间:2015-09-14 02:28:52

标签: javascript google-apps-script

我有一个名为" TEST FOLDER"我有两个电子表格,TEST1和TEST2,我还有一个名为MASTER的电子表格。我想在MASTER Spreadsheet中有一个脚本,它可以在Trigger上运行,每天运行一次。它将通过" TEST FOLDER"中的任何SPREADSHEET运行。并将所有新行复制到MASTER SHEET中。我会把"复制"在列中有一个值来检查以确保没有行被复制两次。

   var folder = DocsList.getFolder("TEST FOLDER"); 
   var contents = folder.getFiles();
   var file; 
   var data;

  for (var i = 0; i < contents.length; i++) { file = contents[i];
  if (file.getFileType() == "SPREADSHEET") {
  continue;
 }                                            
  var s = SpreadsheetApp.getActiveSpreadsheet(); 
  var startRow = 2; 
  var numRows = sheet.getLastRow();  
  var dataRange = sheet.getRange(startRow, 1, numRows, 6);
  var data = dataRange.getValues();
  var copied = row[5]; //copied indicator cell

  if(copied != "Copied")
  {
    var target = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("MASTER");
    var targetSheet = target.getRange(rowIndex, nameCol).getValue();
    if (target.getSheetByName(targetSheet)) {
      // set our target sheet and target range
      var targetSheet = ss.getSheetByName(targetSheet);
      var targetRange = targetSheet.getRange(targetSheet.getLastRow()+1, 1, 1, colNumber);
      var sourceRange = s.getRange(rowIndex, 1, 1, colNumber);
      sourceRange.copyTo(targetRange);
      sheet.getRange(startRow + i, 6).setValue("Copied");
      SpreadsheetApp.flush();
    }
   }
 }

到目前为止,这是我的代码。我

1 个答案:

答案 0 :(得分:2)

我改变了一点代码,这个必须工作。请根据您的文件结构进行调整

function getDataToMaster() {
  var folder = DriveApp.getFolderById("IdOfFolder"); //Define id of folder
  var contents = folder.getFiles();
  var file; 
  var data;
  var sheetMaster = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0]; //first sheet of the file, change by getSheetByName("NAME") if you want
  while(contents.hasNext()){  
    file = contents.next();
    if (file.getMimeType() == "application/vnd.google-apps.spreadsheet") {
      var sheet = SpreadsheetApp.openById(file.getId()).getSheets()[0];//first sheet of the file, change by getSheetByName("NAME") if you want
      var startRow = 2; 
      var data = sheet.getDataRange().getValues();
      var colToCheck = 6;
      for(var j = 1; j < data.length;j++){
        if(data[j][colToCheck-1] != "copied"){
          sheetMaster.appendRow(data[j]);
          sheet.getRange((j+1), colToCheck).setValue("copied");
          SpreadsheetApp.flush();
        }
      }
    } 
  }
}

斯特凡