javascript - 我需要使用 JavaScript 循环运行一个有效的 Google App 脚本。 (PDF邮件合并)

标签 javascript google-apps-script

经过一番修补后,我成功获得了一个很好的 PDF 邮件合并 Google 应用程序脚本,可以满足我的需求。我现在的问题是,我希望“邮件合并 PDF”功能在电子表格中的每一行上运行,也许在遇到空白行时停止。我想会有一种更有效的方法,使用数组。说到这里,我有点不知所措了。

我尝试尽可能地记录代码以使其可重用。该脚本在当前状态下运行良好,尽管它仅限于处理单行。

问候 新_2_代码

// Create Custom Scripts Menu in the Google Sheet this script resides in and where the data is housed.
function onOpen() {
    var menuEntries = [{
        name: "Long Service Award Generator",
        functionName: "PDFMailMerge"
    }];
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    ss.addMenu("Custom Scripts", menuEntries);
}

function PDFMailMerge() {

    // Enter the ID of the Google Docs Document you wish to use as a Template for your Document.
    var sleepINT = 1500
    var templateid = "1g0-ydpw_ZsKjcRZ_yKgaqHFFf56DmP4orA1t1MNFpPA"; // template file id
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    ss.toast("10%: Template Sheet Aquired.");
    Utilities.sleep(sleepINT);

    var sheet = ss.getActiveSheet();
    var data = sheet.getRange(2, 1, 1, 15).getValues();
    ss.toast("25%: Template data captured.");
    Utilities.sleep(sleepINT);

    // Make a copy of the Long Service Award template, then Fill up it up with the data from the Long Service Award Spreadsheet. 
    for (var i in data) {
        var row = data[i];
        var docid = DriveApp.getFileById(templateid).makeCopy().getId();
        var doc = DocumentApp.openById(docid);
        var body = doc.getActiveSection();
        body.replaceText("%Preferred_Name%", row[0]);
        body.replaceText("%Last_Name%", row[1]);
        body.replaceText("%Emp_No%", row[2]);
        body.replaceText("%EMAIL%", row[3]);
        body.replaceText("%Personnel_Sub_Area_Desc%", row[4]);
        body.replaceText("%Personnel_Sub_Area_Desc%", row[5]);
        doc.saveAndClose();
    }
    ss.toast("40%: Template data has been replaced.");
    Utilities.sleep(sleepINT);

    //Specifiy a Google Drive Folder by it's URL ID below.
    //Create a duplicate of the newly modified Template to the specified folder, then delete the originally modified Template from the specified folder.
    var file = DriveApp.getFileById(doc.getId());
    var newfolder = DriveApp.getFolderById("1x3uJOuXvKMeoZpWXV7g5nJ_tujMXymaO");
    var oldfolder = DriveApp.getFolderById("1x3uJOuXvKMeoZpWXV7g5nJ_tujMXymaO");
    newfolder.addFile(file);
    oldfolder.removeFile(file);
    ss.toast("60%: Template has been put in correct folder.");
    Utilities.sleep(sleepINT);


    //Customizing the Template Title
    var usernamefordoctitle = sheet.getRange(2, 1, 1, 1).getValues() // this is grabbing the customer name field (A2)
    var name = doc.getName();
    doc.setName('Template Name for ' + usernamefordoctitle);
    ss.toast("70%: named new Long Service Award");
    Utilities.sleep(sleepINT);

    //Set a Google Drive Folder's URL ID below, .PDF Files generated through this method will be stored in this folder.
    //Create a PDF File using the Modified Template created earlier in the script and name the resulting .PDF file according to the Template Title
    var pdffolder = DriveApp.getFolderById("1x3uJOuXvKMeoZpWXV7g5nJ_tujMXymaO");
    var pdfFILE = DriveApp.getFileById(doc.getId()).getAs('application/pdf');
    pdfFILE.setName(doc.getName() + ".pdf");
    var theFolder = pdffolder;
    var theFile = DriveApp.createFile(pdfFILE);
    theFolder.addFile(theFile);
    ss.toast("80%: PDF generated");
    Utilities.sleep(sleepINT);

    //Send an email to recepient (Email Values in Colmun D) - Attatch PDF File Created Earlier.
    var pdfEMAIL = DriveApp.getFileById(doc.getId()).getAs('application/pdf').getBytes();
    var message = "Hi " + usernamefordoctitle + "!, please kindly find your invoice attached.\nMany Thanks!\nMe";
    var emailAdd = sheet.getRange("D2").getValue()
    var emailTo = emailAdd; // add customer email here
    var subject = "Long Service Award for " + usernamefordoctitle;

    var attach = {
        fileName: 'Long Service Award for ' + usernamefordoctitle + '.pdf',
        content: pdfEMAIL,
        mimeType: 'application/pdf'
    };
    MailApp.sendEmail(emailTo, subject, message, {
        attachments: [attach]
    });
    ss.toast("90%: " + usernamefordoctitle + "has been emailed.");
    Utilities.sleep(sleepINT);

    ss.toast("100%: Template for " + usernamefordoctitle + " has been created. Doc ID: " + docid);
    Utilities.sleep(sleepINT);
}

更新: 我尝试过实现嵌套的 for 循环。我目前没有取得太大成功。该脚本执行时没有错误,但仅处理第一行。 (等于“sheet.getLastRow()”的长度。)

对于格式不正确的代码提前表示歉意。我已经筋疲力尽,无法正确编辑它。

代码如下:

// Create Long Service Award Menu in Google Sheet this script resides in and where the data is housed.
function onOpen() {
  var menuEntries = [ {name: "Test", functionName: "PDFMailMerge"}];
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  ss.addMenu("Custom Scripts", menuEntries);
}

function PDFMailMerge() {

//Super Loop
var ss2 = SpreadsheetApp.getActiveSpreadsheet();
var sheet2 = ss2.getActiveSheet();
for(var index2 = 1; index2 < sheet2.getLastRow(); index2++)
{
    var data2 = sheet2.getRange(index2,1,1,15).getValues();
    for (var i in data2) {
        var row = data2[i];
        //your code here
  
  
  // Enter the ID of the Google Docs Document you wish to use as a Template for your Document.
  var sleepINT = 1500
  var templateid = "1g0-ydpw_ZsKjcRZ_yKgaqHFFf56DmP4orA1t1MNFpPA"; // template file id
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  ss.toast("10%: Template Sheet Aquired.");
  Utilities.sleep(sleepINT);
  
  var sheet = ss.getActiveSheet();
  var data = sheet.getRange(2,1,1,15).getValues();                                           
  ss.toast("25%: Template data captured."); 
  Utilities.sleep(sleepINT);

if (index2 < sheet.getLastRow()){
for (var j = 0; j < sheet.getLastRow(); j++)
{var data = sheet.getRange(1+j,1,1,15).getValues();
j++}
}
else {
ss.toast("Error")
}

//var data needs to increment
// Make a copy of the Long Service Award template, then Fill up it up with the data from the Long Service Award Spreadsheet. 
for (var i in data) {
var row = data[i];
var docid = DriveApp.getFileById(templateid).makeCopy().getId();
var doc = DocumentApp.openById(docid);
var body = doc.getActiveSection();
body.replaceText("%Preferred_Name%", row[0]);
body.replaceText("%Last_Name%", row[1]);
body.replaceText("%Emp_No%", row[2]);
body.replaceText("%%Personnel_Sub_Area%%", row[4]);
body.replaceText("%Personnel_Sub_Area_Desc%", row[5]);
doc.saveAndClose();
}
ss.toast("40%: Template data has been replaced.");
Utilities.sleep(sleepINT);

//Specifiy a Google Drive Folder by it's URL ID below.
//Create a duplicate of the newly modified Template to the specified folder, then delete the originally modified Template from the specified folder.
var file = DriveApp.getFileById(doc.getId());
var newfolder = DriveApp.getFolderById("1x3uJOuXvKMeoZpWXV7g5nJ_tujMXymaO");
var oldfolder = DriveApp.getFolderById("1x3uJOuXvKMeoZpWXV7g5nJ_tujMXymaO");
newfolder.addFile(file);
oldfolder.removeFile(file);    
ss.toast("60%: Template has been put in correct folder.");
Utilities.sleep(sleepINT);


if (index2 < sheet.getLastRow()){
for (var p = 1; p < sheet.getLastRow(); p++)
{var usernamefordoctitle = sheet.getRange(2, 1, 1, 1).getValues();
p++}
// Column in range in usernamefordoctitle must increment up   
//Customizing the Template Title
var usernamefordoctitle = sheet.getRange(2, 1, 1, 1).getValues() // this is grabbing the customer name field (A2)
var name = doc.getName();
doc.setName('Template Name for ' + usernamefordoctitle);
ss.toast("70%: named new Long Service Award");
Utilities.sleep(sleepINT);
}
else {
var usernamefordoctitle = sheet.getRange(2, 1, 1, 1).getValues() // this is grabbing the customer name field (A2)
var name = doc.getName();
doc.setName('Template Name for ' + usernamefordoctitle);
ss.toast("70%: named new Long Service Award");
Utilities.sleep(sleepINT);
}

//Does not need incrememnting - The value for usernamefordoctitle is used here which is incrememented
//Set a Google Drive Folder's URL ID below, .PDF Files generated through this method will be stored in this folder.
//Create a PDF File using the Modified Template created earlier in the script and name the resulting .PDF file according to the Template Title
var pdffolder = DriveApp.getFolderById("1x3uJOuXvKMeoZpWXV7g5nJ_tujMXymaO");
var pdfFILE = DriveApp.getFileById(doc.getId()).getAs('application/pdf');
pdfFILE.setName(doc.getName() + ".pdf");
var theFolder = pdffolder;
var theFile = DriveApp.createFile(pdfFILE);
theFolder.addFile(theFile);
ss.toast("80%: PDF generated");
Utilities.sleep(sleepINT);

if (index2 < sheet.getLastRow()){
for (var k = 0; k < sheet.getLastRow(); k++)
{var data = sheet.getRange(1+k,1,1,15).getValues();
k++}
}
else {
ss.toast("Error")
}
//email add needs to be changed to get value and be incrememented
//Send an email to recepient (Email Values in Colmun D) - Attatch PDF File Created Earlier.
var pdfEMAIL = DriveApp.getFileById(doc.getId()).getAs('application/pdf').getBytes();
var message = "Hi " + usernamefordoctitle + "!, please kindly find your invoice attached.\nMany Thanks!\nMe";
var emailAdd = sheet.getRange("D2").getValue()
var emailTo = emailAdd; // add customer email here
var subject = "Long Service Award for " + usernamefordoctitle;
        
var attach = {fileName:'Long Service Award for ' + usernamefordoctitle + '.pdf',content:pdfEMAIL, mimeType:'application/pdf'};
MailApp.sendEmail(emailTo, subject, message, {attachments:[attach]});
ss.toast("90%: " + usernamefordoctitle + "has been emailed.");
Utilities.sleep(sleepINT);  

ss.toast("100% Template for " + usernamefordoctitle + " has been created. Doc ID: "); 
Utilities.sleep(sleepINT);
  }
}
}

最佳答案

var sheet = ss.getActiveSheet();
for(var index = 1; index < sheet.getLastRow(); index++)
{
    var data = sheet.getRange(index,1,1,15).getValues();
    for (var i in data) {
        var row = data[i];
        //your code here
    }
}

关于javascript - 我需要使用 JavaScript 循环运行一个有效的 Google App 脚本。 (PDF邮件合并),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47947462/

相关文章:

javascript - 如何修复 Jasmine 中的 'TypeError: Cannot redefine property: origin'

javascript - 在单击任何对象之前,Angular 2 不会更新

javascript - Ajax 错误`Uncaught TypeError : Illegal invocation when making ajax call

google-apps-script - Google Apps 脚本 : Multiple recipients in GmailApp?

javascript - 有没有办法在不取消运行的情况下查看谷歌应用程序脚本中的记录器?

google-apps-script - 当中间有空单元格时如何跳到最后一行?

javascript - 理解回调和相关的词法范围

javascript - 获取动态字符串的最后 2 个字符

javascript - Google 表单文件上传 - 如何使用通过表单提交的图像并将其嵌入电子邮件中

google-apps-script - 如何删除谷歌图表并将其替换为谷歌应用程序中的新图表?