Google App脚本优化

时间:2017-02-15 19:03:00

标签: google-apps-script google-sheets

好的,我需要帮助优化(如果可能)并错误检查我的代码。

我的代码已经运行了20多个星期没有错误。现在突然间,剧本“挂起”了。在第190行执行.setvalues时。这是存档信息的部分。

收到的错误是"服务超时:电子表格" "例外:服务错误:电子表格"

脚本在星期日凌晨2点到凌晨运行,此时服务器应该不那么拥挤。手动运行时,脚本也从未超时。即使工作数据增加三倍或四倍,我也无法复制此错误。

所以,我会开始。

我的脚本分为4个部分。

第1节:

验证信息 - 删除过滤器,取消隐藏行/列并删除空行。

第2节:

将所选工作表复制到新电子表格,然后通过电子邮件将其作为Excel格式的附件发送给选定用户。

第3节:

清除原始工作表中的数据以防止重复的可能性。

第4节:

这是失败的部分,请将复制的值复制并粘贴到存档的电子表格中。

以前,没有循环重新尝试这个。如果失败,我会收到一封包含excel文件的电子邮件。

循环似乎没有帮助。除此之外,它在本周末将一半的信息粘贴到我的档案中。

如果这有帮助,正在移动的数据大约是8000行和15列,因此大约有120,000个单元格。 (没那么多)

如果有人可以提出任何修改或改进建议,请随意。

以下完整代码。

//******************** Menu Start ************************//

   function onOpen() {
   var ui = SpreadsheetApp.getUi();
   ui.createMenu('Admin')
      .addItem('Update to Raw', 'moveData')
      .addSeparator()
      .addSubMenu(ui.createMenu('Authorise')
          .addItem('Authorise Scripts', 'Auth'))
      .addToUi();
}

//******************** Menu End ************************//

//******************** Authorisation Start ************************//

function Auth(){

  var email = Session.getActiveUser().getEmail();
var temp = new Date();
  if (temp == "Blank") {
    // These calls will never be visited
onOpen();
moveData();
clearData();
RemoveFilter();
DeleteBlankRows();
UnhideAllRowsAndColumns();
UnhideAllRowsAndColumnsRaw();
clearDataRaw();

  } else {
    Browser.msgBox("The Backup script has now been authorized for "+email+". Each user only has to do this once.");
  }
}

//******************** Authorisation End ************************//

//******************** Clear Source Sheet Start ************************//

function clearData() {

  var Spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var source = Spreadsheet.getSheetByName("Data");

  source.deleteRows(2,source.getLastRow()-1);

}

//******************** Clear Source Sheet End ************************//

//******************** Copy Data Start ************************// 

function ArchiveData() {

  var Spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var source = Spreadsheet.getSheetByName("Data");
  var targetkey = Spreadsheet.getSheetByName("Archive").getRange("C1").getValue();
  var tSpreadsheet = SpreadsheetApp.openById(targetkey);
  var target = tSpreadsheet.getSheetByName("Raw");

try{

  // Information Quality Checks

RemoveFilter();
UnhideAllRowsAndColumns();
DeleteBlankRows();


  var storedata = source.getRange(2,1,source.getLastRow(),source.getLastColumn()).getValues();
  var sn = Spreadsheet.getName();
  var URL = Spreadsheet.getUrl();
  var message = URL;
  var date = Utilities.formatDate(new Date(), "GMT+1", "dd-MM-yyyy HH:mm");

  var subject = sn + " - Script Complete :  " + date;

  var emailTo = ["Recipient1@gmail.co.uk","Recipient2@gmail.co.uk",
                "Recipient3@gmail.co.uk","Recipient4@gmail.co.uk","Recipient5@gmail.co.uk"];

  // Google Sheets Extract Sheet Hack //
  // Create a new Spreadsheet and copy the current sheet into it//

  var newSpreadsheet = SpreadsheetApp.create("Call Log Script Export");
  source.copyTo(newSpreadsheet);

  newSpreadsheet.getSheetByName('Sheet1').activate();
  newSpreadsheet.deleteActiveSheet();
 // newSpreadsheet.getSheetByName('!Copied Sheet Name!').setName("Source Export") //

  var ssID = newSpreadsheet.getId();
  var url = "https://docs.google.com/spreadsheets/d/" + ssID + "/export?format=xlsx&id=" + ssID;

  var requestData = {"method": "GET","headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};

  var result = UrlFetchApp.fetch(url , requestData); 
  var contents = result.getContent();

  MailApp.sendEmail(emailTo, subject, message, 
  {attachments:[{fileName:"Call Log Script Export.xls", content:contents, mimeType:"application//xls"}]});




//------------------------- Move Data -------------------------//

  var senddata = target.getRange(target.getLastRow()+1, 1, source.getLastRow(),source.getLastColumn() );

//------------------------- Clear Data Call -------------------------//
        // ------------- Clears Source Sheet ------------- //

clearData();

var retryLimit = 4;
var retryDelay = 1000;
var retry;
    for (retry = 0; retry <= retryLimit; retry++) {
      try {
        // do the spreadsheet operation that might fail
        senddata.setValues(storedata);

          // Delete the wasted sheet we created, so our Drive stays tidy
        DriveApp.getFileById(ssID).setTrashed(true);
        SpreadsheetApp.flush();
        break; 
      }
      catch (e) {
        Logger.log('Failed on try ' + retry + ', exception: ' + e);
        if (retry == retryLimit) {
          throw e; 
        }
        Utilities.sleep(retryDelay);
      }  
  }

//------------------------- Copy Data Mid -------------------------//

}

//------------------------- Catch and Send Error Start -------------------------//


catch(err){
var error = err.lineNumber + ' - ' + err;
var URL = Spreadsheet.getUrl();
var sn = Spreadsheet.getName();
var date = Utilities.formatDate(new Date(), "GMT+1", "dd-MM-yyyy HH:mm");

var emailadd = ["Recipient1@gmail.co.uk","Recipient2@gmail.co.uk",
                    "Recipient3@gmail.co.uk","Recipient4@gmail.co.uk","Recipient5@gmail.co.uk"];
var subject = sn + " : Archive Script Error";
var body = URL + " - - - Date - - - " + date + " - - - Error Code - - - " +     error

MailApp.sendEmail(emailadd,subject,body);

 }

//------------------------- Catch and Send Error End -------------------------//

}

//******************** Copy Data End ************************//

//******************** Unhide Start ************************// 

function UnhideAllRowsAndColumns() {

  var Spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var source = Spreadsheet.getSheetByName("Data");

var fullSheetRange = source.getRange(1,1,source.getMaxRows(), source.getMaxColumns() )  
source.unhideColumn( fullSheetRange );
source.unhideRow( fullSheetRange ) ;  
  }  

//******************** Unhide End ************************// 

//******************** Delete Blank Start ************************// 

function DeleteBlankRows() {

  var Spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var source = Spreadsheet.getSheetByName("Data");

  var rows = source.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();

  var rowsDeleted = 0;
  for (var i = 0; i <= numRows - 1; i++) {
    var row = values[i];
    if (row[1] == '') {
      source.deleteRow((parseInt(i)+1) - rowsDeleted);
      rowsDeleted++;
    }
  }
}

//******************** Delete Blank End ************************// 

//******************** Remove Filter Start ************************// 

function RemoveFilter(){

  var Spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var source = Spreadsheet.getSheetByName("Data");

var row = 1 //the row with filter 
var rowBefore = row 

source.insertRowBefore(row); //inserts a line before the filter
row++;

var Line = source.getRange(row + ":" + row); //gets filter line in A1N
Line.moveTo(source.getRange(rowBefore + ":" + rowBefore)); //move to new     line in A1N
source.deleteRow(row); //deletes the filter line

}

//******************** Remove Filter End ************************// 

3 个答案:

答案 0 :(得分:0)

我仔细查看了代码,但我没有看到任何明显的问题。但我对这条线很好奇:

var senddata = target.getRange(target.getLastRow()+1, 1, source.getLastRow(),source.getLastColumn() );

由于我无法看到您的数据,因此我无法确认senddata的范围高度和宽度是否与storageata的尺寸相同,如果它们不是,那么这可能会导致问题

答案 1 :(得分:0)

所以这就是困扰我的事情:

  var storedata = source.getRange(2,1,source.getLastRow(),source.getLastColumn()).getValues();
    var senddata = target.getRange(target.getLastRow()+1, 1, source.getLastRow(),source.getLastColumn() );

storedata is an array that has to have the same dimensions as the range senddata. 
number of rows in the storedata range is source.getLastRow()-1. 
number of columns in the storedata range is source.getLastColumn() = 15

number of rows in senddata is source.getLastRow() - target.getLastRow() + 1
number of columns in senddate is source.getLastColumn() = 15

so:
source.getLastRow()-1 = source.getLastRow() - target.getLastRow() + 1
add 1 to both sides
source.getLastRow() = source.getLastRow() - target.getLastRow() + 2 
subtract source.getLastRow() from both sides
target.getLastRow() = 2 //is this true

这总是如此吗?或者我在这里完全是标记。

答案 2 :(得分:0)

  

&#34;服务超时:电子表格&#34;

今天我的脚本上发生了错误,经过几次试验后,我可以做的就是:

  • 制作工作表的完整副本(包含脚本)并开始使用该工作表。

干杯,