首页 > 解决方案 > 根据谷歌表格信息创建个性化的谷歌表单

问题描述

假设我在 google 表格中有一个电子表格,其中包含 EMAIL、TOPIC 和 TIME 三个列,我想向电子表格中的每个 EMAIL 发送一封电子邮件,其中包含指向 google 表单的链接,该表单有一个问题,询问首选 TIME在电子表格中给出主题。基于表格创建这种个性化的谷歌表单是否可行?

标签: google-apps-script

解决方案


应该做的第一件事是创建表单并发送电子邮件。为此,我编写了一个函数,该函数循环遍历工作表中的所有行(称为“Sheet1”,根据您的喜好进行更改),为每一行创建一个表单并将其发送到 A 列中的电子邮件(在我一直在处理的工作表,数据从第 2 行开始,列是:A - 电子邮件 / B - 主题 / C - 时间):

function sendMails() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var values = ss.getSheetByName("Sheet1").getDataRange().getValues();
  for(var i = 1; i < values.length; i++) {
    var email = values[i][0];
    var topic = values[i][1]
    var formName = email + " - " + topic;
    var form = FormApp.create(formName);
    var url = form.getPublishedUrl();
    form.setTitle(formName);
    form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId()); // This line bounds the created form to your spreadsheet so that responses will be written in here, in an automatically created sheet
    // You can set another destination spreadsheet if you don't want all these sheets created in your spreadsheet
    var question = form.addDateTimeItem();
    question.setTitle("Please provide a preferred time for your assigned lecture on " + topic);
    var userEmail = form.addCheckboxItem();
    userEmail.setChoices([userEmail.createChoice(email)]);
    var topicName = form.addCheckboxItem();
    topicName.setChoices([topicName.createChoice(topic)]);
    var checkBoxValidation = FormApp.createCheckboxValidation()
    .requireSelectExactly(1)
    .build();
    userEmail.setValidation(checkBoxValidation);
    topicName.setValidation(checkBoxValidation);
    MailApp.sendEmail(email, topic, url);
  }
}

接下来,您需要在电子表格中安装 onFormSubmit 触发器。您可以执行此操作来运行一个函数,该函数将在每次提交表单时写入用户在表单中选择的首选时间。要创建触发器,只需在脚本中运行此函数一次:

function createOnFormSubmitTrigger() {
  var ss = SpreadsheetApp.getActive();
  ScriptApp.newTrigger('writeTime')
      .forSpreadsheet(ss)
      .onFormSubmit()
      .create();
}

最后,下面是提交表单时触发器触发的功能。它查找主题和电子邮件与来自表单的主题和电子邮件匹配的行,并设置时间:

function writeTime(e) {
  var response = e.values;
  var time = response[1];
  var email = response[2];
  var topic = response[3];
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  var values = sheet.getDataRange().getValues();
  for(var i = 1; i < values.length; i++) {
    if(values[i][0] == email && values[i][1] == topic) {
      sheet.getRange(i + 1, 3).setValue(time);
    }
  }
}

我希望这对你有用。


推荐阅读