【问题标题】:Run Google script on single sheet instead of entire spreadsheet在单张而不是整个电子表格上运行 Google 脚本
【发布时间】:2018-01-30 14:01:39
【问题描述】:

使用我的电子表格,我将 2 个 Google 表单绑定到 2 张工作表上。当表单被提交时,脚本执行并完成它的事情。但是,我只希望脚本基于来自单个工作表的提交来执行。就像现在一样,脚本会在任一表单提交时执行。

我的两张纸是: 作业提交 并提交订单

有什么建议吗?

// Work Order


// Get template from Google Docs and name it
var docTemplate = "";  // *** replace with your template ID ***
var docName     = "Work Order";
var printerId   = "";

function addDates() {
    var date = new Date(); // your form date
    var holiday = ["09/04/2017","10/09/2017","11/23/2017","12/24/2017","12/25/2017","01/01/2018"]; //Define holiday dates in MM/dd/yyyy
    var days = 5; //No of days you want to add
    date.setDate(date.getDate());
    var counter = 0;
        if(days > 0 ){
            while (counter < days) {
                date.setDate(date.getDate() + 1 ); 
                var check = date.getDay(); 
                var holidayCheck = holiday.indexOf(Utilities.formatDate(date, "EDT", "MM/dd/yyyy"));
                  if (check != 0 && check != 6  && holidayCheck == -1) {
                         counter++;
                    }
            }
        }
        Logger.log(date) //for this example will give 08/16/2017
    return date;
}

function createNewDoc(values) {
//Get information from form and set as variables
  var email_address = "";
  var job_name = values[1];
  var order_count = values[2];
  var order_form = values[7];
  var print_services = values[3];
  var priority = values[5];
  var notes = values[6];
  var formattedDate = Utilities.formatDate(new Date(), "EDT", "MM/dd/yyyy");
  var expirationDate = Utilities.formatDate(addDates(), "EDT", "MM/dd/yyyy");

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

// Replace place holder keys,in our google doc template  
   copyBody.replaceText('keyJobName', job_name);
   copyBody.replaceText('keyOrderCount', order_count);
   copyBody.replaceText('keyOrderForm', order_form);
   copyBody.replaceText('keyPrintServices', print_services);
   copyBody.replaceText('keyPriority', priority);
   copyBody.replaceText('keyNotes', notes);
   copyBody.replaceText('keyDate', formattedDate);
   copyBody.replaceText('keyDue', expirationDate);

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

// Convert temporary document to PDF by using the getAs blob conversion
   var pdf = DriveApp.getFileById(copyId).getAs("application/pdf"); 

// Attach PDF and send the email
   var subject = "New Job Submission - " + job_name;
   var body    = "Here is the work order for " + job_name + ". Job is due " + expirationDate + ".";
   MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf}); 

// Move file to folder
   var file = DriveApp.getFileById(copyId);
   DriveApp.getFolderById("").addFile(file);
   file.getParents().next().removeFile(file);

   var newDocName = docName + ' for ' + job_name;
   return [copyId, newDocName];
}

function printGoogleDocument(copyId, docName) {  
  // For notes on ticket options see https://developers.google.com/cloud-print/docs/cdd?hl=en
  var ticket = {
    version: "1.0",
    print: {
      color: {
        type: "STANDARD_COLOR"
      },
      duplex: {
        type: "NO_DUPLEX"
      },
    }
  };

  var payload = {
    "printerid" : "",
    "content"   : copyId,
    "title"  : docName,
    "contentType" : "google.kix", // allows you to print google docs
    "ticket"    : JSON.stringify(ticket),
  };

  var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
    method: "POST",
    payload: payload,
    headers: {
      Authorization: 'Bearer ' + GoogleCloudPrint.getCloudPrintService().getAccessToken()
    },
    "muteHttpExceptions": true
  });

  // If successful, should show a job here: https://www.google.com/cloudprint/#jobs

  response = JSON.parse(response);
  if (response.success) {
    Logger.log("%s", response.message);
  } else {
    Logger.log("Error Code: %s %s", response.errorCode, response.message);
  }
  return response;
}

// When Form Gets submitted
function onFormSubmit(e) { 
  var values = e.values;
  var returnedDocValues = createNewDoc(values);
  var copyId = returnedDocValues[0];
  var docName= returnedDocValues[1];
  printGoogleDocument(copyId, docName);
}

编辑: 我不确定如何做一个完整或可验证的示例,因为它取决于表单提交。我不经常使用 javascript,所以我还在学习。

无论如何,我更新了我的 onFormSubmit 函数,但是我的其他函数未能执行。该脚本不会创建文档,因此不会发送到谷歌云打印

// When Form Gets submitted
function onFormSubmit(e) { 
// Initialize
  var rng = e.range;
  var sheet = rng.getSheet();
  var name = sheet.getName();
// If the response was not submitted to the right sheet, exit.
  if(name != "Job Submission") return; 
  var values = e.values;
  var returnedDocValues = createNewDoc(values);
  var copyId = returnedDocValues[0];
  var docName= returnedDocValues[1];
  printGoogleDocument(copyId, docName);
}

【问题讨论】:

  • 有没有办法只在特定的工作表上执行脚本?不一定要看表单,只在Sheet1有新表单提交时运行脚本。
  • 最好发minimal reproducible example而不是完整代码。
  • 不知道如何做一个可验证的代码,因为它依赖于表单,但我已经更新了有问题的函数。
  • 您是否将触发失败通知设置为立即发送?您确定表单正在将回复发送到“作业提交”表吗?
  • 每天都会发生触发器故障。是的,响应会填充在作业提交表中。

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


【解决方案1】:

如果您的 onFormSubmit 函数在绑定到电子表格的脚本上,则事件对象包括一个范围对象。您可以使用 getSheet 获取工作表,然后使用 getName 获取工作表名称。

例子:

function onFormSubmit(e){
  // Initialize
  var rng = e.range;
  var sheet = rng.getSheet();
  var name = sheet.getName();

  // If the response was not submitted to the right sheet, exit.
  if(name != "Responses 1") return; 

  //Otherwise continue
}

【讨论】:

  • 我将您的建议添加到我的函数中,但它无法运行 // 当表单获取提交函数 onFormSubmit(e) { // 初始化 var rng = e.range; var sheet = rng.getSheet(); var name = sheet.getName(); // 如果响应没有提交到右表,则退出。 if(name != "作业提交") return; var 值 = e.values; var returnedDocValues = createNewDoc(values); var copyId = returnedDocValues[0]; var docName=returnedDocValues[1]; printGoogleDocument(copyId, docName); }
  • @Brandon:很难阅读 cmets 上的代码。请将其添加到您的问题中或创建一个新问题。
  • 并描述“它无法运行”是什么意思
  • 是的,对不起,我试图找出 cmets 中的降价。我会澄清的。
【解决方案2】:

按照鲁​​本的建议,这就是我最终的结果

function onFormSubmit(e) {
  // Initialize
  var name = e.range.getSheet().getName();
  // If the response was not submitted to the right sheet, exit.
  if (name != "Job Submission") return;
  var values = e.values;
  var returnedDocValues = createNewDoc(values);
  var copyId = returnedDocValues[0];
  var docName = returnedDocValues[1];
  printGoogleDocument(copyId, docName);
}

【讨论】:

    猜你喜欢
    • 2023-03-28
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多