提问者:小点点

如何使用Google表格脚本编辑器制作表单


我需要创建一个有3列的谷歌工作表(列A:姓名,列B:性别和列C:电子邮件)

然后我需要在工作表中添加一个脚本来制作一个表单(由于某些原因我不能使用google表单),其中包含我们刚刚在工作表中添加的三个相关问题

我可以做form. html代码,但我不太熟悉JavaScript将表单连接到提交后的工作表

我想大概是这样的:

function doGet(e) {
  return HtmlService.createHtmlOutputFromFile('form.html');
}

function update spreadsheet {
  var sheet = "get active spreadsheet"
  ...

我无法完成上述代码,有人可以帮助我吗?


共1个答案

匿名用户

您可以将Apps Script部署为Web App[1]。您需要创建一个html文件[2],在其中放置您想要的表单。这里[3]很好地解释了如何在html中使用JavaScript执行Apps Script函数。最后,在Apps Script函数中,您可以使用SpreadsheetApp类插入您想要的值[4]。

这将是在留档中找到的示例代码:

index. html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script>
      // Prevent forms from submitting.
      function preventFormSubmit() {
        var forms = document.querySelectorAll('form');
        for (var i = 0; i < forms.length; i++) {
          forms[i].addEventListener('submit', function(event) {
            event.preventDefault();
          });
        }
      }
      window.addEventListener('load', preventFormSubmit);

      function handleFormSubmit(formObject) {
        google.script.run.withSuccessHandler(updateUrl).processForm(formObject);
      }
      function updateUrl(url) {
        var div = document.getElementById('output');
        div.innerHTML = '<a href="' + url + '">Got it!</a>';
      }
    </script>
  </head>
  <body>
    <form id="myForm" onsubmit="handleFormSubmit(this)">
      <input name="myFile" type="file" />
      <input type="submit" value="Submit" />
    </form>
    <div id="output"></div>
 </body>
</html>

code.gs

function doGet() {
  return HtmlService.createHtmlOutputFromFile('Index');
}

function processForm(formObject) {
  var formBlob = formObject.myFile;
  var driveFile = DriveApp.createFile(formBlob);
  return driveFile.getUrl();
}

[1] https://developers.google.com/apps-script/guides/web

[2] https://developers.google.com/apps-script/guides/html/

[3] https://developers.google.com/apps-script/guides/html/communication

[4] https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app