如何从 google 工作表侧边栏访问和写入数据

How to access and write data from google sheets sidebar

我正在尝试访问 google 工作表侧边栏表单中的值。一直试图找到解决方案太久了。 我无法访问表单中的值并将它们写入电子表格。

知道我做错了什么吗?

应用脚本代码如下:

function showSidebar() {
  var html = HtmlService.createTemplateFromFile('userform')
      .evaluate()
      .setTitle('User Form');
  SpreadsheetApp.getUi()
      .showSidebar(html);
}

function appendData(data){
  var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("UserData");
  ws.appendRow([data.name, data.phone])
}

HTML :

<!DOCTYPE html>
  <html>
    <head>
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    </head>
    <body>
    <div class="container">
      <div class="row">
        <div class="input-field col s12">
          <i class="material-icons prefix">account_circle</i>
          <input id="username" type="text" class="validate">
          <label for="username">Your Name</label>
        </div>
        <div class="input-field col s12">
          <i class="material-icons prefix">phone</i>
          <input id="tel" type="text" class="validate">
          <label for="tel">Telephone</label>
        </div>
        <div class="input-field col s12">
          <button class="btn waves-effect waves-light" id="btn">Submit
            <i class="material-icons right">send</i>
          </button>
        </div>
      </div>
    </div>

    <scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js
</script>    
    <script>

      var nameBox = document.getElementByID("username");
      var phoneBox = document.getElementByID("tel");
      document.getElementByID("btn").addEventListener("click",addRecord);

      function addRecord(){
          var data = {
            name = nameBox.value
            phone  = phoneBox.value
          };          
          google.script.run.appendData(data);          
      }

    </script>
    </body>
  </html>
  • 将出现此方法的getElementByID更改为getElementById
var nameBox = document.getElementById("username");
var phoneBox = document.getElementById("tel");
document.getElementById("btn").addEventListener("click",addRecord);
  • 使用输入字段中的 data 创建一个对象。所以 addRecord() 应该是:
function addRecord(){
  var data = {
    name: nameBox.value,
    phone: phoneBox.value
  };          
  google.script.run.appendData(data);          
}

希望对您有所帮助。