You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从HTML对话框输入框获取值并设置Google Sheets单元格内容

解决Google Sheets对话框复选框同步单元格值的问题

你的代码有两个核心问题需要修正:

  • 前端HTML的客户端脚本无法直接调用SpreadsheetApp这类服务端API,必须通过google.script.run桥接调用服务端函数
  • 复选框的选中状态要读取checked属性,而非value(复选框的value默认固定为"on",和选中状态无关)

以下是修正后的完整代码:

修正后的Code.gs

function onOpen() {
  const ui = SpreadsheetApp.getUi();
  ui.createMenu('My Menu')
      .addItem('Run something', 'doSomething')
      .addToUi();
}

function doSomething() {
  var html = HtmlService.createTemplateFromFile("HTML");
  SpreadsheetApp.getUi().showModalDialog(html.evaluate(),"Make a choice");
}

// 新增服务端函数:接收布尔值并设置A1单元格
function setA1Value(isChecked) {
  const spread = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = spread.getSheetByName("Sheet1");
  sheet.getRange('A1').setValue(isChecked);
}

修正后的HTML.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>

  <body>
    <input type="checkbox" id="all">
    <label for="all"> Tick if all</label>

    <button name="cancel" onclick="google.script.host.close()">Cancel</button>
    <button name="ok" onclick="getValue()">OK</button>
  </body>

  <script>
    function getValue() {
      // 获取复选框的选中状态(布尔值:true/false)
      const isChecked = document.getElementById('all').checked;
      // 调用服务端函数传递值,成功后关闭对话框
      google.script.run
        .withSuccessHandler(() => {
          google.script.host.close();
        })
        .setA1Value(isChecked);
    }
  </script>
</html>

逻辑说明

  1. 点击对话框的OK按钮时,前端脚本读取复选框的checked属性(返回true/false)
  2. 通过google.script.run调用服务端的setA1Value函数,把布尔值传过去
  3. 服务端函数收到值后,将Sheet1的A1单元格设置为对应的布尔值
  4. 操作成功后关闭对话框

内容的提问来源于stack exchange,提问作者RD55297631

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 21:23:24