如何从HTML对话框中运行Apps Script函数?



编辑:它现在都工作了,我只是试着用Edge而不是Chrome运行它,不管出于什么原因,它都工作了。感谢所有回复的人!

我试图使用谷歌应用程序脚本,写到使用自定义对话框中的按钮谷歌表的下一行的脚本。我决定采用这种方法,因为我需要手动处理大量数据,并且在Google Sheet中创建一个带有一些复选框的对话框是我的团队决定采用的方法。

我的问题似乎是使用google.script.run.writeToSheet()不能正常工作。My Executions选项卡显示writeToSheet每次调用时都失败,但是当我在onOpen函数中调用writeToSheet时,它会按预期工作。我是用错了google。script。run还是什么?

下面是我的Apps脚本代码:

function onOpen() {
writeToSheet();
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.addMenu("Detection", [{name: "Detection", functionName: "showDialog"}])
}
function showDialog() {
var html = HtmlService.createHtmlOutputFromFile('Index')
.setWidth(500)
.setHeight(450);
SpreadsheetApp.getUi().showModalDialog(html, "Marine Mammal Detection");
}
function writeToSheet() {
var curSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lastRow = curSheet.getLastRow();
var cellRange = "D"+String(lastRow+1)+":G"+String(lastRow+1);
curSheet.getRange(cellRange).setValues([['g', 'g', 'g', 'g']]);
}
这是我的HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<input type="button" value="Submit" onclick="addDetection()"/>
<script>
function onFailure(error) {
google.script.host.close();
}
function onSuccess(error) {
//google.script.host.close();
}
function addDetection() {
google.script.run.withSuccessHandler(onSuccess).withFailureHandler(onFailure).writeToSheet();
//google.script.host.close();
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<input type="button" value="Submit" onclick="addDetection();"/>
<script>
function addDetection() {
google.script.run.writeToSheet();
}
</script>
</body>
</html>

GS:

function writeToSheet() {
const sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
sh.getRange(sh.getLastRow() + 1 , 1, 1, 4).setValues([[1,2,3,4]]);
}

试试这个,并提供逗号分隔的值:

function writeToSheet(v) {
const sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
sh.getRange(sh.getLastRow() + 1 , 1, 1, v.length).setValues([v]);
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<input type="text" id="txt1" />
<input type="button" value="Submit" onclick="addDetection();"/>
<script>
function addDetection() {
let v = document.getElementById('txt1').value.split(',');
google.script.run.writeToSheet(v);
}
</script>
</body>
</html>

最新更新