从应用脚本中的电子表格更新下拉列表

时间:2014-01-27 21:50:00

标签: javascript jquery html google-apps-script

我正在尝试学习Google的HTML服务用户界面服务,并且正在努力弄清楚如何根据电子表格中的数据更新用户界面中的下拉列表。我从this Google Tutorial复制了以下代码,效果很好。但是,如果我想使用和替换下面的

  • 填充下拉列表,它似乎不起作用。

    <p>List of things:</p>
    <ul id="things">
        <li>Loading...</li>
    </ul>
    
    <script
    src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    </script>
    <script>
    // The code in this function runs when the page is loaded.
    $(function() {
      google.script.run.withSuccessHandler(showThings)
          .getLotsOfThings();
    });
    
    function showThings(things) {
      var list = $('#things');
      list.empty();
      for (var i = 0; i < things.length; i++) {
        list.append('<li>' + things[i] + '</li>');
      }
    }
    </script>
    
  • 1 个答案:

    答案 0 :(得分:3)

    以下Apps脚本项目文件使用电子表格数据填充UI中的下拉选择框。在主要的Apps脚本项目文件(默认名称为Code.gs)中,包括:

    function doGet(request) {
      return HtmlService.createTemplateFromFile('DropDown')
             .evaluate().setSandboxMode(HtmlService.SandboxMode.NATIVE); 
    }
    
    
    function getMenuListFromSheet() {
      return SpreadsheetApp.openById(*SPREADSHEET_ID*).getSheets()[0]
             .getRange(2,1,4,1).getValues();  
    }
    

    您需要将* SPREADSHEET_ID *替换为包含您要用于填充选择框的数据的电子表格的ID。此示例将第一个工作表的A2:A5范围中的数据作为要使用的数据(在getRange()函数中定义)。

    另请注意,此示例使用NATIVE沙箱模式,该模式比默认的EMULATED模式更宽容。

    此示例还需要Apps脚本项目中的HTML文件(此处名为“DropDown.html”):

    <p>List of things:</p>
    <ul id="things">
        <li>Loading...</li>
    </ul>
    
    <select id="menu">
      <option></option>
      <option>Google Chrome</option>
      <option>Firefox</option>
    </select>
    
    
    <script
    src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    </script>
    <script>
    // The code in this function runs when the page is loaded.
    $(function() {
      google.script.run.withSuccessHandler(showThings)
          .getMenuListFromSheet();
      google.script.run.withSuccessHandler(showMenu)
          .getMenuListFromSheet();
    });
    
    function showThings(things) {
      var list = $('#things');
      list.empty();
      for (var i = 0; i < things.length; i++) {
        list.append('<li>' + things[i] + '</li>');
      }
    }
    
    function showMenu(menuItems) {
      var list = $('#menu');
      list.find('option').remove();  // remove existing contents
    
      for (var i = 0; i < menuItems.length; i++) {
        list.append('<option>' + menuItems[i] + '</option>');
      }
    }
    
    </script>
    

    此HTML文件由单个列表和单个选择框组成,两者都具有默认内容。加载页面时,两者的内容将替换为getMenuListFromSheet()函数提供的内容,该函数从电子表格中提取其返回值。

    您可以创建绑定到电子表格容器的这些Apps脚本项目文件,然后将它们发布为Web应用程序。

    相关问题