Google App脚本电子表格

时间:2014-02-27 05:21:14

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

这是代码

function makeaCVdoc(){


var sheet = SpreadsheetApp.getActiveSpreadsheet();

  var startRow = 2;
  var numRows = sheet.getLastRow() -1;
  var EMAIL_SENT = "EMAIL_SENT";
  var subject = "Here is your CV";

  //var dataRange = sheet.getRange(2,2,numRows,50);

  var data = dataRange.getValues();

  for(var i = 0; i < data.length; ++i)
  {

var row = data[i];

var firstname = row[1];
var secondname = row[2];
var thiredname = row[3];
var address = row[4]
var email_address = row[5];
var homenumber = row[6];
var mobilenumber= row[7];
var objective = row[8];
var language = row[9];
var educationwithdegree = row[10];
var computerskill = row[11];
var TrainingCourse = row[12];
var Hobbies = row[13];
var DOB = row[14];
var nationality = row[15];
var MaritalStatus = row[16]
var emailSent = row[17];

var CVdoc = DocumentApp.create(firstname+' '+secondname+' '+thiredname);
var par1 = CVdoc.getBody().appendParagraph(firstname+' '+secondname+' '+thiredname);
par1.setHeading(DocumentApp.ParagraphHeading.TITLE);
var par2 = CVdoc.getBody().appendParagraph("Address: ");
par2.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(address);
var par3 = CVdoc.getBody().appendParagraph("Email Address: ");
par3.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(email_address);
var par4 = CVdoc.getBody().appendParagraph("Home Number: ");
par4.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(homenumber);
var par5 = CVdoc.getBody().appendParagraph("Mobile Number: ");
par5.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(mobilenumber);
var par6 = CVdoc.getBody().appendParagraph("Objective: ");
par6.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(objective);
var par7 = CVdoc.getBody().appendParagraph("Spoken Languages: ");
par7.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(language);
var par8 = CVdoc.getBody().appendParagraph("Education and Degree: ");
par8.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(educationwithdegree);
var par9 = CVdoc.getBody().appendParagraph("Computer Skills: ");
par9.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(computerskill);
var par10 = CVdoc.getBody().appendParagraph("Training Courses: ");
par10.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(TrainingCourse);
var par11 = CVdoc.getBody().appendParagraph("Hobbies: ");
par11.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(Hobbies);
var par12 = CVdoc.getBody().appendParagraph("Nationality: ");
par12.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(nationality);
var par13 = CVdoc.getBody().appendParagraph("Date Of Birth: ");
par13.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(DOB);
var par14 = CVdoc.getBody().appendParagraph("Marital Status: ");
par14.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(MaritalStatus);
var url = CVdoc.getUrl();
var body = 'Link to your doc: ' + url +'Thank you for using our Tech';
if(emailSent != EMAIL_SENT)
{
  //GmailApp.sendEmail(email_address, subject, body);
  //sheet.getRange(2,17).setValue(EMAIL_SENT);
  SpreadsheetApp.flush();
}


 } 
}

它基本上是一种形式,我想用它来获取所需的所有信息,以便制作简历,并在用户输入所有信息并提交表格后存储在电子表格中,而不是我在此内容中包含此代码电子表格,但注释行有问题,我仍然不知道为什么

我的getRange()命令出错了 这会导致GmailApp命令出现另一个代码错误 现在我把它们作为评论 但无论我做什么,我都不知道出了什么问题 所以任何人都可以帮助我


有些人说他们需要更多有关错误的信息 就像我说错误是在注释行

  var dataRange = sheet.getRange(2,2,numRows,50);
  GmailApp.sendEmail(email_address, subject, body);
  sheet.getRange(2,17).setValue(EMAIL_SENT);

它基本上告诉我线路上的错误 并将该行写为函数 我的意思是getRange(数字,数字,数字,数字);

这就是我得到的所有东西


这是我改变后的代码

function makeaCVdoc() 
{

var sheet = SpreadsheetApp.getActiveSpreadsheet();

  var startRow = 2;
  var numRows = sheet.getLastRow() -1;
  var EMAIL_SENT = "EMAIL_SENT";
  var subject = "Here is your CV";

  var dataRange = sheet.getRange("B2:R2");

  var data = dataRange.getValues();

  for(var i = 0; i < data.length; ++i)
  {

var row = data[i];

var firstname = row[0];
var secondname = row[1];
var thiredname = row[2];
var address = row[3]
var email_address = row[4];
var homenumber = row[5];
var mobilenumber= row[6];
var objective = row[7];
var language = row[8];
var educationwithdegree = row[9];
var computerskill = row[10];
var TrainingCourse = row[11];
var Hobbies = row[12];
var DOB = row[13];
var nationality = row[14];
var MaritalStatus = row[15]
var emailSent = row[16];

var CVdoc = DocumentApp.create(firstname+' '+secondname+' '+thiredname);
var par1 = CVdoc.getBody().appendParagraph(firstname+' '+secondname+' '+thiredname);
par1.setHeading(DocumentApp.ParagraphHeading.TITLE);
var par2 = CVdoc.getBody().appendParagraph("Address: ");
par2.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(address);
var par3 = CVdoc.getBody().appendParagraph("Email Address: ");
par3.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(email_address);
var par4 = CVdoc.getBody().appendParagraph("Home Number: ");
par4.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(homenumber);
var par5 = CVdoc.getBody().appendParagraph("Mobile Number: ");
par5.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(mobilenumber);
var par6 = CVdoc.getBody().appendParagraph("Objective: ");
par6.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(objective);
var par7 = CVdoc.getBody().appendParagraph("Spoken Languages: ");
par7.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(language);
var par8 = CVdoc.getBody().appendParagraph("Education and Degree: ");
par8.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(educationwithdegree);
var par9 = CVdoc.getBody().appendParagraph("Computer Skills: ");
par9.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(computerskill);
var par10 = CVdoc.getBody().appendParagraph("Training Courses: ");
par10.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(TrainingCourse);
var par11 = CVdoc.getBody().appendParagraph("Hobbies: ");
par11.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(Hobbies);
var par12 = CVdoc.getBody().appendParagraph("Nationality: ");
par12.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(nationality);
var par13 = CVdoc.getBody().appendParagraph("Date Of Birth: ");
par13.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(DOB);
var par14 = CVdoc.getBody().appendParagraph("Marital Status: ");
par14.setHeading(DocumentApp.ParagraphHeading.HEADING2);
CVdoc.getBody().appendParagraph(MaritalStatus);
CVdoc.saveAndClose();
var CVdocID = CVdoc.getId();
var url = CVdoc.getUrl();
var pdf = DocsList.getFileById(CVdocID).getAs("application/pdf");
var body = 'Here is your CV ' + pdf +'Thank you for using our Tech';
if(emailSent != EMAIL_SENT)
{
  GmailApp.sendEmail(email_address, subject, body);
  sheet.getRange("r2").setValue(EMAIL_SENT);
  SpreadsheetApp.flush();


  }
  } 
  sheet.deleteRow(2);
}

1 个答案:

答案 0 :(得分:1)

我不确定如何解决你的问题,我怀疑它是结构,而且你在getRange中拉了50列,但实际上只需要17列(可能的列宽错误?)这是我用来从表单提交程序生成文档的脚本。在我的情况下,我在完成后删除了该文档,但是您将其留在那里并收集URL并将其附在您吐出的电子邮件中。你也可以使用链式函数来重复一些重复的任务,比如copyBody.replaceText(“text”,variable),但是如果我给你的那个版本,那就更麻烦了,因为我使用了很多for()迭代器,并且该示例中的数据来自UiApp,而不是表单和电子表格组合。

  function onFormSubmit(e) { // add an onsubmit trigger
  var sheet = SpreadsheetApp.getActiveSheet();
  var row =  SpreadsheetApp.getActiveSheet().getLastRow();
  //Set Unique ID for each entry
  sheet.getRange(row,2).setValue(row);

  // Full name and email address values come from the spreadsheet form
  var email_address = "myemail@somewhere.com";//used as a reporting email for errors
  var userName = e.values[1];
  var date     = e.values[2];
  var vendor = e.values[3];
  var coordinator = e.values[4];
  var buyer = e.values[5];
  var category = e.values[7];
  var submittedBy = e.values[79];


  //Values from form
  var line1 = e.values[9];
  var item1 = e.values[10];
  var quantity1 = e.values[11];
  var sku1 = e.values[12];
  var price1 = e.values[13];
  var total1 = e.values[14];

  var line2 = e.values[16];
  var item2 = e.values[17];
  var quantity2 = e.values[18];
  var sku2 = e.values[19];
  var price2 = e.values[20];
  var total2 = e.values[21];

  var line3 = e.values[23];
  var item3 = e.values[24];
  var quantity3 = e.values[25];
  var sku3 = e.values[26];
  var price3 = e.values[27];
  var total3 = e.values[28];

  var line4 = e.values[30];
  var item4 = e.values[31];
  var quantity4 = e.values[32];
  var sku4 = e.values[33];
  var price4 = e.values[34];
  var total4 = e.values[35];

  var line5 = e.values[37];
  var item5 = e.values[38];
  var quantity5 = e.values[39];
  var sku5 = e.values[40];
  var price5 = e.values[41];
  var total5 = e.values[42];

  var line6 = e.values[44];
  var item6 = e.values[45];
  var quantity6 = e.values[46];
  var sku6 = e.values[47];
  var price6 = e.values[48];
  var total6 = e.values[49];

  var line7 = e.values[51];
  var item7 = e.values[52];
  var quantity7 = e.values[53];
  var sku7 = e.values[54];
  var price7 = e.values[55];
  var total7 = e.values[56];

  var line8 = e.values[58];
  var item8 = e.values[59];
  var quantity8 = e.values[60];
  var sku8 = e.values[61];
  var price8 = e.values[62];
  var total8 = e.values[63];

  var line9 = e.values[65];
  var item9 = e.values[66];
  var quantity9 = e.values[67];
  var sku9 = e.values[68];
  var price9 = e.values[69];
  var total9 = e.values[70];

  var line10 = e.values[72];
  var item10 = e.values[73];
  var quantity10 = e.values[74];
  var sku10 = e.values[75];
  var price10 = e.values[76];
  var total10 = e.values[77];

  var sumRange = sheet.getRange(1,86,sheet.getLastRow(),1);
  sumRange.setNumberFormat("0,000,000.00");

  sheet.getRange(row,86,1,1).setNumberFormat("0,000,000.00");
  var sum = Math.round(100*(sheet.getRange(row,86,1,1).getValue())/100);
  Logger.log(sum);
  sheet.getRange(row,86,1,1).setNumberFormat("0,000,000.00");
  Logger.log(sum);


  //Document variables
  var docTemplate = "Doc Id for your template document to replace text";  // *** replace with your template ID ***
  var todaysDate = Utilities.formatDate(new Date(), "GMT", "MM/dd/yyyy");
  var docName     = "CV Document name " +userName +" on " +todaysDate;

  // Get document template, copy it as a new temp doc, and save the Doc’s id
  var copyId = DocsList.getFileById(docTemplate)
  .makeCopy(docName)
  .getId();
  // Open the temporary document
  var copyDoc = DocumentApp.openById(copyId);
  // Get the document’s body section
  var copyBody = copyDoc.getActiveSection();

  // Replace place holder keys this can be iterated with a number of for() loops
  // Template Header
  copyBody.replaceText('keyDate', date);   
  copyBody.replaceText('keyVendor', vendor);
  copyBody.replaceText('keyCoordinator', coordinator);
  copyBody.replaceText('keyBuyer', buyer);
  copyBody.replaceText('keyCategory', category);

  //Template Table
  copyBody.replaceText('keyLine1', line1);   
  copyBody.replaceText('keyItem1', item1);
  copyBody.replaceText('keyQuantity1', quantity1);
  copyBody.replaceText('keySKU1', sku1);
  copyBody.replaceText('keyPrice1', price1);
  copyBody.replaceText('keyTotal1', total1);

  copyBody.replaceText('keyLine1', line1);   
  copyBody.replaceText('keyItem1', item1);
  copyBody.replaceText('keyQuantity1', quantity1);
  copyBody.replaceText('keySKU1', sku1);
  copyBody.replaceText('keyPrice1', price1);
  copyBody.replaceText('keyTotal1', total1);

  copyBody.replaceText('keyLine2', line2);   
  copyBody.replaceText('keyItem2', item2);
  copyBody.replaceText('keyQuantity2', quantity2);
  copyBody.replaceText('keySKU2', sku2);
  copyBody.replaceText('keyPrice2', price2);
  copyBody.replaceText('keyTotal2', total2);

  copyBody.replaceText('keyLine3', line3);   
  copyBody.replaceText('keyItem3', item3);
  copyBody.replaceText('keyQuantity3', quantity3);
  copyBody.replaceText('keySKU3', sku3);
  copyBody.replaceText('keyPrice3', price3);
  copyBody.replaceText('keyTotal3', total3);

  copyBody.replaceText('keyLine4', line4);   
  copyBody.replaceText('keyItem4', item4);
  copyBody.replaceText('keyQuantity4', quantity4);
  copyBody.replaceText('keySKU4', sku4);
  copyBody.replaceText('keyPrice4', price4);
  copyBody.replaceText('keyTotal4', total4);

  copyBody.replaceText('keyLine5', line5);   
  copyBody.replaceText('keyItem5', item5);
  copyBody.replaceText('keyQuantity5', quantity5);
  copyBody.replaceText('keySKU5', sku5);
  copyBody.replaceText('keyPrice5', price5);
  copyBody.replaceText('keyTotal5', total5);

  copyBody.replaceText('keyLine6', line6);   
  copyBody.replaceText('keyItem6', item6);
  copyBody.replaceText('keyQuantity6', quantity6);
  copyBody.replaceText('keySKU6', sku6);
  copyBody.replaceText('keyPrice6', price6);
  copyBody.replaceText('keyTotal6', total6);

  copyBody.replaceText('keyLine7', line7);   
  copyBody.replaceText('keyItem7', item7);
  copyBody.replaceText('keyQuantity7', quantity7);
  copyBody.replaceText('keySKU7', sku7);
  copyBody.replaceText('keyPrice7', price7);
  copyBody.replaceText('keyTotal7', total7);

  copyBody.replaceText('keyLine8', line8);   
  copyBody.replaceText('keyItem8', item8);
  copyBody.replaceText('keyQuantity8', quantity8);
  copyBody.replaceText('keySKU8', sku8);
  copyBody.replaceText('keyPrice8', price8);
  copyBody.replaceText('keyTotal8', total8);

  copyBody.replaceText('keyLine9', line9);   
  copyBody.replaceText('keyItem9', item9);
  copyBody.replaceText('keyQuantity9', quantity9);
  copyBody.replaceText('keySKU9', sku9);
  copyBody.replaceText('keyPrice9', price9);
  copyBody.replaceText('keyTotal9', total9);

  copyBody.replaceText('keyLineA', line10);   
  copyBody.replaceText('keyItemA', item10);
  copyBody.replaceText('keyQuantityA', quantity10);
  copyBody.replaceText('keySKUA', sku10);
  copyBody.replaceText('keyPriceA', price10);
  copyBody.replaceText('keyTotalA', total10);

  copyBody.replaceText('keySum', +sum);

  // Save and close the temporary document
  copyDoc.saveAndClose();
  // Convert temporary document to PDF by using the getAs blob conversion
  var pdf = DocsList.getFileById(copyId).getAs("application/pdf"); 
  // Attach PDF and send the email
  var subject = "CV submitted by "+submittedBy;
  var body    = userName +" has submitted a new CV, which is attached to this email.\nPlease ensure there are no errors before printing.\nIf there are errors, please notify: "+email_address +"\n\n";
  MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf}); 
  // Delete temp file
  DocsList.getFileById(copyId).setTrashed(true);//remove this if you added URL above for posterity
}

如果您感兴趣,我可以发布此代码的迭代器版本,为重复操作创建循环。请告诉我。它比这个例子复杂得多,因为有很多函数调用,但是如果你对此感到满意,我会把它放在上面。

我知道这个代码会生成发票类型/运输标签文件,因为我的模板是以这种方式构建的。我没有将代码更改为您的变量和需求。您还需要构建一个带有键的模板文档,以替换每个用户的条目值,但这并不是非常困难。所有格式都可以在那里完成,您可以在从提交的数据列中读取的脚本中添加标题等,这样如果该部分(例如国籍)留空,则没有标题或内容。

您正在寻找本教程http://googleappsdeveloper.blogspot.com/2011/10/4-ways-to-do-mail-merge-using-google.html中的技巧#3,以获取有关如何执行我提供的脚本的指南。

另外,请注意使用数字键的body.replaceText()。当你到达10时,它将用keyText1替换文本并在末尾添加一个0字符串。我建议您使用字母或单词代替您的keyValues。

这是同一基本过程的迭代函数版本。忽略UiApp行并删除app方法,它将像表单一样工作。我将它作为一种替代方法,以展示如何使用for循环从模板构造文档,而无需手动编写所有代码。它也更模块化,所以如果我需要更改某些内容,我可以添加或修改该功能,而不是弄乱其余部分。

function doPost(e){
  var app = UiApp.getActiveApplication();
  var vertPanel = app.createVerticalPanel();
  var grantName = e.parameter.grantName;
  var userEmail = Session.getActiveUser().getEmail();
  var mrNumber = e.parameter.MR;
  var ss = SpreadsheetApp.openById("Id for the form response spreadsheet");
  var infoSheet = ss.getSheetByName('name of the form response sheet');
  var keyRow = selectKeysByGrant(grantName);
  var keyHeaders = infoSheet.getRange(1,1,1,infoSheet.getLastColumn()).getValues();
  var infoData = infoSheet.getRange(keyRow,1,1,infoSheet.getLastColumn()).getValues();
  var keyIds = new Array (makeKeys(keyHeaders));
  var dataVars = new Array (makeDataVars(keyIds));
  var copyId = assignKeys(dataVars,keyIds,infoData,userEmail,mrNumber);
  var pdf = mailCheatSheet(copyId,userEmail,mrNumber);
  var completeLabel = app.createLabel('You should receive your worksheet results in your email soon.');
  app.add(completeLabel);
  return app;

  }

//Select Data Row from funding type
function selectKeysByGrant(grantName){
  var grant = null;
  switch (grantName){
    case "1":
      grant = 2
      break;
    case "2":
      grant = 3
      break;
    case "3":
      grant = 4
      break;
    case "4":
      grant = 5
      break;
  }
  return grant;
}

function makeKeys(keyHeaders){
  var keys = [];
  for (var i = 0; i< keyHeaders[0].length; i++){
    keys.push("key"+keyHeaders[0][i]);
  }
  return keys;
}

function makeDataVars(keyIds){
  var dataVarLabels = [];
  for (var k = 0; k < keyIds[0].length; k++){
    dataVarLabels.push(keyIds[0][k] +"text");
  }
  return dataVarLabels;
}


function assignKeys(dataVars,keyIds,infoData,userEmail,mrNumber){
  var variables = dataVars;
  var keys = keyIds;
  var rowData = infoData;
  var userEmail = userEmail;
  var date = Utilities.formatDate(new Date, "CST","MM/dd/yyyy");
  var mrNum = mrNumber;
  Logger.log(variables);
  Logger.log(keys);
  Logger.log(rowData);

  var docTemplate = "ID of your document template";
  var todaysDate = Utilities.formatDate(new Date(), "GMT", "MM/dd/yyyy");
  var docName     = "New name of document created submitted by " +userEmail +" on " +todaysDate;

  // Get document template, copy it as a new temp doc, and save the Doc’s id
  var copyId = DocsList.getFileById(docTemplate).makeCopy(docName).getId();
  // Open the temporary document
  var copyDoc = DocumentApp.openById(copyId);
  // Get the document’s body section
  var copyBody = copyDoc.getActiveSection();

   for (n = 1; n < variables[0].length; n++){
     copyBody.replaceText(keys[0][n].toString(),rowData[0][n].toString())
   }
  //replacing some text from the UIapp but isn't on the spreadsheet
  copyBody.replaceText('keyUserEmail',userEmail);
  copyBody.replaceText('keyDate',date);
  copyBody.replaceText('keyMR',mrNum);


  // Save and close the temporary document
  copyDoc.saveAndClose();
  return copyId;

}

function mailCheatSheet(copyId,userEmail,mrNumber){
  var copyId = copyId;
  var userEmail = userEmail;
  var mrNum = mrNumber;
  // Convert temporary document to PDF by using the getAs blob conversion
  var pdf = DocsList.getFileById(copyId).getAs("application/pdf"); 
  // Attach PDF and send the email
  var subject = "SA Funding request by: "+userEmail;
  var body    = userEmail +" has submitted a document for " +mrNumber +", which is attached to this email.\nPlease ensure there are no errors before printing.\nIf there are errors, please notify: myself@xyz.com.\n\n";
  MailApp.sendEmail(userEmail, subject, body, {name: 'CV Helperbot', htmlBody: body, attachments: pdf}); 
  // Delete temp file
  DocsList.getFileById(copyId).setTrashed(true);
  return pdf;
}