脚本过早清理数据,有人知道原因吗?

时间:2016-01-12 21:10:45

标签: javascript email pdf google-apps-script google-sheets

因此,我正在使用脚本编写Google表格中的项目,最终会执行以下操作;

首先,根据单元格中的名称,在表单回复中找到该人的最后9个条目。

然后以我需要的方式安排数据并将其写入工作表中的工作表

脚本的最后一部分(不是我自己的工作,而是我在这里找到的东西) Script I found online 我已经尝试适应我的需求,还没有完全适应我的需求。创建PDF,将其保存在谷歌驱动器中,然后通过电子邮件发送。

这部分需要更多的工作,因为我想指定使用名称和日期调用PDF的内容。另外,我想指定它在谷歌中的保存位置。最后,该脚本只生成一个PDF。想最终复制脚本,以便我可以创建1个PDF或批量创建它们。如果我遇到困难,可能会在以后发布这些内容。

所以无论如何这是概述。

目前,该脚本可以运行,可以查询我想要的数据,将其写入工作表,将其保存为PDF格式,并通过电子邮件发送到单个硬编码的电子邮件地址。迷死。

但是我接着尝试添加一个名为clearRanges的函数,它会在写入数据之前清除模板表。我使用名称范围来定义要清除的3个部分。但是自从介绍它以来,我已经在我的脚本的各个部分尝试过了。我的驱动器和电子邮件中都有空白的PDF格式。

它不等待在清除数据之前创建PDF或发送电子邮件。我也试图把它放在我的脚本的开头,但同样的事情。不明白为什么。

我正在玩lock和waitlock作为一种可能的解决方案,但它似乎没有帮助。

如果有人可以提供帮助,我会很感激。

  function getAgentName() {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      Browser.msgBox("Please go to the sheet called PDF Creator, in cell A2, choose the agent you wish to create a PDF for");
      var sheet = ss.getSheetByName("PDF Creator");
      var range = sheet.getRange("A2")
      var value = range.getValue();

      if (value == 0) {
          Browser.msgBox("You need to go to the sheet named PDF Creator and put an agent name in cell A2");
      } else {
          getAgentData(value);
      }
  }

  function getAgentData(value) {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sourceSheet = ss.getSheetByName("Form responses 1")
      var sourceRange = sourceSheet.getDataRange();
      var sourceValues = sourceRange.getValues();
      var agentData = [];
      var commentsData = [];

      for (i = 0; i < sourceValues.length; i++) {
          // Defines the data layout for PDF.
          var agentName = sourceValues[i][2];
          var dateTime = sourceValues[i][3];
          var callType = sourceValues[i][7];
          var opening = sourceValues[i][8];
          var rootCause = sourceValues[i][9];
          var rootFix = sourceValues[i][10];
          var process = sourceValues[i][11];
          var consumer = sourceValues[i][12];
          var control = sourceValues[i][13];
          var wrapup = sourceValues[i][14];
          var dpa = sourceValues[i][15];
          var score = sourceValues[i][22];
          var comments = sourceValues[i][16];
          var agentRow = [dateTime, callType, opening, rootCause, rootFix, process, consumer, control, wrapup, dpa, score];
          var commentsRow = [dateTime, comments];

          if (agentName == value && agentData.length < 9) {
              agentData.push(agentRow)
              commentsData.push(commentsRow)
          }
      }

      agentData.sort(function (a, b) {
          return b[0] - a[0]
      });

      commentsData.sort(function (a, b) {
          return b[0] - a[0]
      });

      var destSheet = ss.getSheetByName("AgentPDF");
      destSheet.getRange("A1").setValue(value + "'s Quality Score card");
      var range = destSheet.getRange(6, 1, agentData.length, agentData[0].length);
      range.setValues(agentData);
      var commentRange = destSheet.getRange(18, 1, commentsData.length, commentsData[0].length);
      commentRange.setValues(commentsData);
      emailSpreadsheetAsPDF();
  }

  /* Send Spreadsheet in an email as PDF, automatically */
  function emailSpreadsheetAsPDF() {
      // Send the PDF of the spreadsheet to this email address
      var email = "firstname.lastname@domain.co.uk";
      // Subject of email message
      // The date time string can be formatted in your timezone using Utilities.formatDate method
      var subject = "PDF Reports - " + (new Date()).toString();
      // Get the currently active spreadsheet URL (link)
      // Or use SpreadsheetApp.openByUrl("<<SPREADSHEET URL>>");
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      // Email Body can  be HTML too with your logo image - see ctrlq.org/html-mail
      var body = "PDF generated using code at ctrlq.org from sheet " + ss.getName();
      var url = ss.getUrl();
      url = url.replace(/edit$/, '');
      /* Specify PDF export parameters
  // From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
    exportFormat = pdf / csv / xls / xlsx
    gridlines = true / false
    printtitle = true (1) / false (0)
    size = legal / letter/ A4
    fzr (repeat frozen rows) = true / false
    portrait = true (1) / false (0)
    fitw (fit to page width) = true (1) / false (0)
    add gid if to export a particular sheet - 0, 1, 2,..
  */
      var url_ext = 'export?exportFormat=pdf&format=pdf' // export as pdf
      + '&size=a4' // paper size
      + '&portrait=1' // orientation, false for landscape
      + '&fitw=true&source=labnol' // fit to width, false for actual size
      + '&sheetnames=false&printtitle=false' // hide optional headers and footers
      + '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
      + '&fzr=false' // do not repeat row headers (frozen rows) on each page
      + '&gid=928916939'; // the sheet's Id
      var token = ScriptApp.getOAuthToken();
      //  var sheets = ss.getSheets(); 
      //make an empty array to hold your fetched blobs  
      var blobs = [];
      //  for (var i=0; i<sheets.length; i++) {
      // Convert individual worksheets to PDF
      //    var response = UrlFetchApp.fetch(url + url_ext + sheets[i].getSheetId(), {
      var response = UrlFetchApp.fetch(url + url_ext, {
          headers: {
              'Authorization': 'Bearer ' + token
          }
      });

      //convert the response to a blob and store in our array
      blobs[0] = response.getBlob().setName("Tester " + '.pdf');
      //  }
      //create new blob that is a zip file containing our blob array
      //  var zipBlob = Utilities.zip(blobs).setName(ss.getName() + '.zip'); 
      var test = DriveApp.createFile(blobs[0]);
      //optional: save the file to the root folder of Google Drive
      DriveApp.createFile(test);
      // Define the scope
      Logger.log("Storage Space used: " + DriveApp.getStorageUsed());

      // If allowed to send emails, send the email with the PDF attachment
      if (MailApp.getRemainingDailyQuota() > 0)
          var lock = LockService.getScriptLock();
      GmailApp.sendEmail(email, subject, body, {
          attachments: [test]
      });

      lock.waitLock(20000);
      lock.releaseLock();
      clearRanges();
  }

  function clearRanges() {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      ss.getRangeByName('Header').clearContent();
      ss.getRangeByName('Scores').clearContent();
      ss.getRangeByName('Comments').clearContent();
  }

1 个答案:

答案 0 :(得分:2)

您可以尝试添加SpreadsheetApp.flush(); 在致电emailSpreadsheetAsPDF();

之前在第60行附近

SpreadsheetApp.flush()

commentRange.setValues(commentsData); SpreadsheetApp.flush(); emailSpreadsheetAsPDF();

我之前遇到过类似的问题而且这很有用。

相关问题