Google apps脚本HTML选择从电子表格数据加载的选项

google apps script html select options loaded from spreadsheet data

本文关键字:数据 加载 选项 电子表格 apps 脚本 HTML 选择 Google      更新时间:2023-09-26

新的google apps脚本,javascript等…

尝试在电子表格中创建一个侧边栏,该侧边栏包含一个html选择对象,该对象是从其中一个工作表中的列填充的。

我已经尝试过使用我在这篇文章中发现的代码,但是加载选项的函数在加载html时似乎没有执行。知道我哪里做错了吗?

code in code.gs:

function onOpen(e) {
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .createMenu('USD Conversion')
      .addItem('Convert Dollars to Foreign Currency', 'showSidebar')
      .addToUi();
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var csvMenuEntries = [{name: "Load rates from CSV file", functionName: "importFromCSV"}];
  var addCountriesMenuEntries = [{name: "Add Countries", functionName: "addCountries"}];
  var conversionEntries = [{name: "Convert Dollars for Foreign Currency", functionName: "showSidebar"}];
}
/**
 * Opens a sidebar in the document containing the add-on's user interface.
 */
function showSidebar() {
  var template = HtmlService
      .createTemplateFromFile('Sidebar')
  var htmlOutput = template.evaluate()
      .setSandboxMode(HtmlService.SandboxMode.IFRAME)
      .setTitle('USD Conversion')
      .setWidth(400);
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .showSidebar(htmlOutput);
}
function getListOptions() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("CountryCodes");
  var lastRow = sheet.getLastRow();  
  var myRange = sheet.getRange("P2:P"+lastRow); 
  var countries = myRange.getValues(); 
  return( countries );
}

code in Sidebar.html:

<div class="labels">
    <p>Destination Country:</p>
</div>
<div>
  <select name="optionList">
    <option>Loading...</option>    
  </select>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>
<script>
    // The code in this function runs when the page is loaded.
    $(function () {
        google.script.run.withSuccessHandler(buildOptionList)
            .getListOptions();
    });
    function buildOptionList(countries) {
        var list = $('#optionList');
        list.empty();
        for (var i = 0; i < countries.length; i++) {
            list.append(countries[i]);
        }
    }
</script>

要在jQuery中通过id引用选择列表,select元素需要一个id属性<select id="optionList" name="optionList">。要向选项列表中添加一个选项,可以使用以下语法:list.append(new Option(countries[i],countries[i]));,其中第一个值是名称,第二个值是值。

你的谷歌脚本代码看起来不错,但你可以在返回语句之前添加Logger.log(countries);,以验证你正在返回预期的结果。在Google Script编辑器中,您可以通过单击Run ->(函数名)来测试函数,然后单击View -> Logs来查看日志。在尝试一起使用Google Script代码和HTML代码之前,最好分别测试它们。