【问题标题】:access a google sheet entry from the embedded html file site从嵌入的 html 文件站点访问 google 工作表条目
【发布时间】:2015-12-20 22:29:00
【问题描述】:

我正在尝试通过谷歌应用脚​​本在谷歌表格的右侧边栏中使用嵌入的 html。访问工作表的单元格并将其显示在 html5 画布元素上。我已经创建了一个 Code.gs 文件和一个 html 索引文件,并且已经成功地让电子表格生成了一个右侧边栏,其内容是包含 Canvas 元素的 HTML 文件。这使用

function openSidebar() {
    var html = HtmlService.createHtmlOutputFromFile('index');
    SpreadsheetApp.getUi().showSidebar(html);
}

现在我想在 Canvas 元素上显示一些电子表格单元格条目。我的第一个任务是使用这种方法在侧边栏上创建一个箱线图。我有五个包含五点摘要的单元格:min、Q1、Median、Q3、Max,但无法让 canvas 元素访问这些值。以下是不起作用的:

通过调用范围直接访问<script> </script>标签之间的单元格,例如:

var range = statsSheet.getRange(4,4);
var min = range.getValue();

它不起作用,因为 statsSheet 是在 Code.gs 文件上创建的。

如果这两行代码直接在 Code.gs 文件中,它们确实可以找到单元格值,但是 html 文件中的代码无法访问 min。

我也尝试创建一个单独的 .gs 文件 (boxPlot.gs) 并使用导入它

<script src = "boxPlot.gs"> </script>

但这仍然行不通。我无法访问变量 min ,因为它是全局变量或 boxPlot.gs 文件中函数的返回值。

如果能提供任何关于如何转换伪代码的帮助,我将不胜感激:&lt;html&gt; create canvas;&lt;script&gt; add min which resides at cell (4,4) as text onto the canvas; &lt;/script&gt;&lt;/html&gt;

谢谢

感谢您的帮助,但我仍然无法将变量的值从 Code.gs 文件传递​​到 index.html 中的 &lt;script&gt; &lt;/script&gt; 代码。使用您的建议,我能够运行 doSomething() 函数,但无法读取返回值。例如在 Code.gs 文件中,我有 做点什么(){ 返回(“你好世界”); }

在html页面中,我有

 <script>
      console.log(google.script.run.doSomething());
 </script>

这会将“未定义”放在控制台上,而不是“Hello World”。 当然,我希望能够读取更复杂的元素,例如表单条目,但如果我什至无法读取“Hello World”返回值,那么复杂的任务将永远无法工作。任何建议将不胜感激。

【问题讨论】:

  • 不要在返回值周围加上括号。只需使用return "Hello World";

标签: javascript google-apps-script google-sheets html5-canvas sidebar


【解决方案1】:

您必须使用 google.script.run 客户端 API 才能从 HTML 访问服务器端代码。

Google Documentation - google.script.run

或使用将运行.gs 服务器函数的scriptlet,并在提供内容之前将内容添加到HTML。这些小脚本仅在第一次打开侧边栏时运行。因此,首次打开侧边栏时,请使用 scriptlet 作为初始内容。

术语是“模板化 HTML”

Google Documentation - Templated HTML

要从服务器接收返回值到 HTML 客户端 JavaScript,您必须使用 .withSuccessHandler(name_of_function_to_receive_return) 方法。

Google Documentation - withSuccessHandler Method

您正在使用以下测试代码:

google.script.run.DoSomething()

为了从服务器接收“返回”,您必须使用withSuccessHandler()

google.script.run
  .withSuccessHandler(functionToHandleTheReturn)
  .DoSomething()

<script>
  function functionToHandleTheReturn(theReturnedValue) {
    alert('here is the returned value: ' + theReturnedValue;
  };
</script>

【讨论】:

  • 谢谢,但我无法获取 google.script.run.DoSomething() 以提供 DoSomething 函数的返回值。在我更详细的编辑帖子底部查看我更详细的评论。谢谢,拉里
  • 感谢一百万!这现在有效,我正在为基本统计创建一个完整的应用程序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
  • 2017-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多