您好我正在尝试使用html和google脚本获取下拉列表。 应从Google电子表格中填充列表的值。在stackoverflow上搜索了很多后,我管理了下面的代码。但我仍然无法从电子表格中获取数据作为下拉选项。没有错误,但我只是得到一个空白的Dropbox作为输出
电子表格链接:https://docs.google.com/spreadsheets/d/1qaxzTWRf4_xDhfkf-_S9Zr2m-M-9blOcpFBt4JyT5do/edit#gid=0
function doGet() {
var template = HtmlService.createTemplateFromFile('Index');
var htmlOutput = template.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
return htmlOutput;
}
< select id = "something" > < option > Choose a option < /option>
</select > < body onload = "addList()" > < /body>
<script>
function addList(){
var sheet = SpreadsheetApp.openById('1qaxzTWRf4_xDhfkf-_S9Zr2m-M-9blOcpFBt4JyT5do').getSheetByName('Sheet1');
var lastRow = sheet.getLastRow();
var myRange = sheet.getRange("C2:C" + lastRow);
var options = new Array()
var select = document.getElementById("something");
var data = myRange.getValues();
for(var i = 0; i < lastRow; i++) {
options.push(data[i]);
}
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
var el = document
el.text = opt;
el.value = opt;
select.appendChild(el);
}
</script >
答案 0 :(得分:0)
您需要完全重构代码。这应该是这样的:
<select id="something">
<option> Choose a option </option>
</select >
<body onload = "addList()"></body>
<script>
function addList() {
console.log('addList ran!');
google.script.run
.withFailureHandler(onFailure)
.withSuccessHandler(injectMyContent)
.getDropDownContent();
};
window.injectMyContent = function(argReturnedData) {
for(var i = 0; i < argReturnedData.length; i++) {
var opt = argReturnedData[i];
var el = document.createElement("option");
var el = document
el.text = opt;
el.value = opt;
select.appendChild(el);
};
};
window.onFailure = function(err) {
alert('There was an error! ' + err.message);
};
</script >
function getDropDownContent() {
var sheet = SpreadsheetApp.openById('Your SS ID').getSheetByName('Sheet1');
var lastRow = sheet.getLastRow();
var myRange = sheet.getRange("C2:C" + lastRow);
var options = new Array()
var select = document.getElementById("something");
var data = myRange.getValues();
for(var i = 0; i < lastRow; i++) {
options.push(data[i]);
}
return options;
};
请注意,此代码仍有错误。我只是为你提供一个起点。我没有提供完美的代码或为您完成所有工作。程序流程的基本结构是正确的,所有功能都被触发。我没有解决注入下拉的细节问题。那里有一个错误。看看你是否能搞清楚。或者也许其他人可以添加评论。