如何将Google电子表格侧边栏中的输入发送到工作表脚本函数?

6
我希望侧边栏上有3个带标签的文本字段和一个按钮,点击按钮应将文本字段内容发送到电子表格脚本函数进行进一步处理。我知道如何创建和显示侧边栏,以及如何通过按钮单击触发脚本函数,但不知道如何发送文本字段内容。
// SidePanel.html
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <button onclick='f1()'>Update the address</button>
<script>
  function f1() {
    google.script.run.getAddress();
  }
</script>
  </body>
</html>

// display sidebar in gs
function showSidebar(){
  var html = HtmlService.createHtmlOutputFromFile('SidePanel').setTitle('Helper').setWidth(100);
  SpreadsheetApp.getUi().showSidebar(html);
}
1个回答

10

以下是一个示例,它将帮助您了解如何从侧边栏向Google表格发送值

HTML代码:

    <!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <button onclick='f1()'>Update the address</button>
    <!-- Create a input field to except a value form user, in this case there name -->
    Your Name:
    <input type="text" id="name"><br>
    <!-- Create a button to send the value to the spreadsheet -->
    <button onclick='sendName()'>Send Name</button>
<script>

  function f1() {
    google.script.run.getAddress();
  }

  function sendName(){
   //Get the value of the input field 
   var name = document.getElementById("name").value
   //Log the value of input field in the web browser console (usually used for debugging)
   console.log(name)
   //Send the value of the text field as a arugment to the server side function.
   google.script.run.enterName(name)
  }
</script>
  </body>
</html>

上面的HTML代码使用输入框从用户获取值。您可以使用DOM方法访问输入字段的值。文本字段的值存储在function sendNames()中的var name中。这将作为参数google.script.run.enterName(name)传递给Google脚本函数。
您的Google脚本(也称为服务器端代码)
function showSidebar(){
  var html = HtmlService.createHtmlOutputFromFile('SO_sideBar_Example').setTitle('Helper').setWidth(100);
  SpreadsheetApp.getUi().showSidebar(html);
}

// Sets the value of A1 cell to value entered in the input field in the side bar!
function enterName(name){
 var ss = SpreadsheetApp.getActive()
 var sheet = ss.getActiveSheet()
 sheet.getRange("A1").setValue(name) 
}

在上述服务器端代码中,function enterName() 接收以单元格A1输入的用户输入作为其参数 name。使用withSuccessHandler()和withFailureHandler()来处理服务器端代码成功或失败的情况,here提供了详细说明。

好的,但我希望三个输入可以在一次点击中发送(每个字段没有单独的按钮)。在您的示例中,gs enterName函数能够处理3个参数吗?即函数enterName(name,address,city)和google.script.run.enterName(name,address,city)分别是什么? - amilewski
我根据我的猜测进行了测试,结果很好。非常感谢你的帮助,杰克。 - amilewski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接