响应 Google 文档自定义 HTML 对话框中的按钮单击事件

Responding to button click events in Google Docs custom HTML dialog

我是 Google 电子表格的管理员。我和其他管理员每周有几次必须将新用户添加到电子表格中,所以我认为如果我们可以使用自定义 HTML 对话框来执行此操作会更容易。

我是这样显示对话框的:

function AddRow()
{
    var html = HtmlService.createHtmlOutputFromFile('AddRow')
                  .setSandboxMode(HtmlService.SandboxMode.IFRAME);
    SpreadsheetApp.getUi().showModalDialog(html, 'Add Row') 
}

文件 AddRow.html 是一个简单的 HTML 表单,包含文本框、select 元素等

现在有什么方法可以让我访问电子表格以使用用户输入的值添加新行?

在 HTML 文件中 AddRow.html 我尝试了以下

<script>
    var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = spreadsheet.getSheetByName('2015');
    sheet.insertRows(2, 1);
</script>

但是这不会插入一行。如果我将 HTML 文件的代码移动到 *.gs 文件中,它确实有效,所以它一定是对 HTML 文件的限制?

提供的 HTML 文件中的脚本代码是 javascript,而不是 Google Apps 脚本 - 这个问题的主要区别在于服务器端 Google Apps 脚本可以访问为 Google 服务提供的全套 API,而客户端 javascript 不能。

一种选择是使用 google.script.run Client-side API to invoke the function that you already have working on the server side (in the editor). For more information, see the guide to communicating with server functions in HTML service

function insertRows(rowIndex, numRows) {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getSheetByName('2015');
  sheet.insertRows(rowIndex, numRows);
  return true;     // Need to have a return value for google.script.run to work
  // To return a failure to the client side, throw an error.
}

客户端脚本:

...
// Call insertRows on server side.
google.script.run
      .withSuccessHandler( hooray )  // See function hooray below
      .insertRows(2, 1);
...

/**
 * This function will receive a call-back if the google.script.run
 * call returns success.
 */
function hooray( result ) {
  alert( "Received result <" + result + ">" );
}