如何将循环结果写入Google表格

时间:2019-02-11 13:25:13

标签: google-apps-script google-sheets

以下代码发送电子邮件,其中包括正文中的表格,数据行和html中的标头。还将相同的数据附加到xlsx和pdf文件中。有些人喜欢pdf,有些喜欢电子邮件正文,有些喜欢xlsx,所以...

我有2个问题,代码如下:

循环的结果(表/行)应写入Google工作表(导出)。然后,此工作表将以PDF和XLSX格式附加到发送的电子邮件中。

当前“导出”工作表已经附加,但是由于尚未将数据写入“导出工作表”,因此它为“空”,这是问题所在吗?

我已经尝试添加“ xlsxTable + = data [row] [col];”行。在代码中捕获数据,但我认为这不是正确的方法。

第二个问题是,有时附件(xlsx)的格式不正确,并且包含以下单词:“此文件可能为un”。 (Google预览)下载xlsx时说的是文件格式不正确……但是奇怪的是,当发送到3封不同的电子邮件时,其中2封可以,1封不正确,有时都可以。也许这是计时问题,应该包括一个暂停。

欢迎任何帮助,谢谢!

下面的代码使用Google工作表,其中包含4个工作表:数据,电子邮件,参数,导出。

数据表

ID    Name      Amount   Date
1000  Company    500.23  01/01/2019
2000  Company    500.23  01/01/2019
1000  Company    500.23  01/01/2019
3000  Company    500.23  01/01/2019
1000  Company    500.23  01/01/2019
2000  Company    500.23  01/01/2019

电子邮件表

ID      To  Cc Bcc FirstName Subject Language BodyStart BodyEnd Sent SentDate
1000    Company1@email.com
2000    Company2@email.com
3000    Company3@email.com

参数表仅包含ReplyTo和ReplyToName

实际代码

function Statements_Attachments() {

  //This section specifies the sheet and some fixed variables.

    var ss = SpreadsheetApp.getActiveSpreadsheet();  
    var dataRange = ss.getSheetByName("Data").getDataRange();
    var emailRange = ss.getSheetByName("Emails").getDataRange();
    var param = ss.getSheetByName("Parameters");
    var data = dataRange.getValues();
    var nameData = emailRange.getValues();
    var lastCol = dataRange.getLastColumn();
    var lastRow = emailRange.getLastRow();
    var replyEmail = param.getRange("B2").getValue();
    var replyName = param.getRange("B3").getValue();
    var sentRange = ss.getSheetByName("Emails");
    var startRow = 1;
    var sent = "Y";

    var ssA = SpreadsheetApp.getActive();
    var ssID = ssA.getId();
    var ssName = ssA.getName();
    var sheetName = "Export";  //Fill in Sheet Name you want to Email
    var shID = getSheetID(sheetName); //Get Sheet ID of Sheet Name

  //This section below starts the loop comparing the key between the 2 sheets.

  for (var i = 1; i < nameData.length; i++) {

    var rows = nameData[i];
    var emailAddress = rows[2]; 
    var keyID = rows[0];
    var ccMail = rows[3];
    var bccMail = rows[4];
    var bodyStart = rows[8]; 
    var bodyEnd = rows[9];
    var keyName = rows[1];
    var subject = rows[6] ;
    var emailSent = rows[10];
    var xlsxTable = "";         //Variable used to collect the Data for pasting in "Export Sheet"
    var exportTable = "";       //Variable used to paste Data in "Export Sheet"
    var htmlTable = "";         // HTML body Table created to paste in Email
    var htmlMessage = "";
    var preTable = '<!DOCTYPE html><html>' + bodyStart ;
    var postTable = '</html>';   

    for (row = 0; row < data.length; row++) {
      if (row == 0){
        for (col = 0; col < data[row].length; col++) {
          if (col == 0) {
              htmlTable += '<tr><th style="border-collapse: collapse;border: 1px solid black;background-color:#558EDB">' + data[row][col] + '</th>';
              xlsxTable += data[row][col];
          } else
          if (col == lastCol - 1) {
              htmlTable += '<th style="border-collapse: collapse;border: 1px solid black;background-color:#558EDB">' + data[row][col] + '</th></tr>';
              xlsxTable += data[row][col];
          } else {
              htmlTable += '<th style="border-collapse: collapse;border: 1px solid black;background-color:#558EDB">' + data[row][col] + '</th>';
              xlsxTable += data[row][col];
          }
        }      
      }
      else if (data[row][0] == keyID) {
        for (col = 0; col < data[row].length; col++) {
          if (col == 0) {
              htmlTable += '<tr><td style="border-collapse: collapse;border: 1px solid black">' + data[row][col] + '</td>';
              xlsxTable += data[row][col];
          } else
          if (col == lastCol - 1) {
              htmlTable += '<td style="border-collapse: collapse;border: 1px solid black">' + data[row][col] + '</td></tr>';
              xlsxTable += data[row][col];
          } else
          if (col == 6) {
              htmlTable += '<td align="right" style="border-collapse: collapse;border: 1px solid black">' + data[row][col] + '</td>';
              xlsxTable += data[row][col];
          } else
          if (col == 20 || col == 21) {
              htmlTable += '<td style="border-collapse: collapse;border: 1px solid black">' + Utilities.formatDate(data[row][col], "GMT", "dd-mm-yyyy") + '</td>';
              xlsxTable += data[row][col];
          } else {
              htmlTable += '<td align="right" style="border-collapse: collapse;border: 1px solid black">' + data[row][col] + '</td>';
              xlsxTable += data[row][col];
          }
        }  
      }
    }


    //The section below closes the table in the body and constructs the complete body.

      htmlTable += '</tbody></table>';
      htmlMessage = preTable + htmlTable + bodyEnd + postTable;


    //The section below should paste the Data into the Export Sheet, to be used as basis for the xlsx & pdf attachment to the email.

      exportTable = xlsxTable;
    //How to write the result to the Export Sheet in columns and rows.

    //The section below sets the variables for the Attachment.

      var url = "https://docs.google.com/spreadsheets/d/"+ ssID + "/export?format=xlsx&id="+ ssID +"&gid="+ shID;
      var urlPdf = url + "&portrait=true" + "&exportFormat=pdf";

      var paramsP = {
        method      : "get",
        headers     : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
        muteHttpExceptions: true
      };

      var paramsX = {
        method      : "get",
        headers     : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
        muteHttpExceptions: true
      };


      var blobPdf = UrlFetchApp.fetch(urlPdf, paramsP).getBlob();
      var blobP = blobPdf.setName(sheetName + ".pdf");

      var blobXlsx = UrlFetchApp.fetch(url, paramsX).getBlob();
      var blobX = blobXlsx.setName(sheetName + ".xlsx");


    //The section below retrieves alias email address to send as

      var me = Session.getActiveUser().getEmail();// Log the aliases for this Gmail account.
      var aliases = GmailApp.getAliases(); // Gets the alias from account
      Logger.log(aliases);  // Logs the alias


    // The section below sends the actual emails

       if (emailAddress != "" && emailSent != sent){   //If next email address needs to be different add: && nextEmail != emailAddress
         if (aliases.length > 0){  // Prevents sending duplicates

         GmailApp.sendEmail(emailAddress, subject, '', {
           htmlBody: htmlMessage,
           from : aliases[1],
           cc : ccMail,
           bcc : bccMail,
           replyTo : replyEmail,
           name : replyName,
           attachments : [blobP, blobX],
         });

    // The section below puts a "Y" next to the row already processed.

          sentRange.getRange(startRow + i, 11).setValue(sent);
          sentRange.getRange(startRow + i, 12).setValue(new Date ());    

          //Utilities.sleep(1000);
          SpreadsheetApp.flush();  // Make sure the cell is updated right away in case the script is interrupted

          }   
        }  
     }
  }


function getSheetID(name){
 var sheetName = SpreadsheetApp.getActive().getSheetByName(name)
 var sheetID = sheetName.getSheetId().toString() 
 return sheetID
}

0 个答案:

没有答案