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

Google Apps Script/Sheets Template Scriplets与脚本调用不生效问题

问题原因

两个异常均为API用法错误导致:

  • 模板代码原样输出:createHtmlOutputFromFile只会直接读取HTML文件的原始文本返回,不会执行<? ?>格式的服务端模板逻辑。要解析模板代码,必须用createTemplateFromFile加载文件,调用evaluate()生成最终HTML后再展示。
  • 点击按钮无内容:google.script.run是异步非阻塞接口,不会直接返回服务端函数的运行结果,必须通过withSuccessHandler绑定回调函数接收返回值,直接用变量接返回值拿到的永远是undefined,自然不会渲染内容。

另外原有CSV转换函数缺少显式的行内拼接逻辑,虽然JS数组默认转字符串会用逗号分隔,但显式指定分隔符能避免边缘场景的格式错乱。

修正后代码

Code.gs

function onOpen() {
  SpreadsheetApp.getUi()
      .createMenu('Custom Menu')
      .addItem('Show sidebar', 'showSidebar')
      .addToUi();
}

function showSidebar() {
  // 替换为模板加载方式,执行evaluate后才会解析服务端模板脚本
  const html = HtmlService.createTemplateFromFile('Page')
      .evaluate()
      .setTitle('My custom sidebar');
  SpreadsheetApp.getUi().showSidebar(html);
}

function testCSV2() {
  const sheetData = SpreadsheetApp.getActiveSheet().getDataRange().getDisplayValues();
  const csvContent = cellArraysToCsv(sheetData);
  Logger.log(csvContent);
  return csvContent;
}

function cellArraysToCsv(data) {
  const quoteRegex = /"/g;
  // 显式指定单行单元格的逗号分隔符,避免格式问题
  return data.map(row => 
    row.map(cellVal => `"${cellVal.replace(quoteRegex, '""')}"`).join(',')
  ).join('\n');
}

Page.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    Hello, world! 
    <input type="button" value="Answers" onclick="getCsvContent()" />
    <h2 id="contentArea"></h2>
    <br><br>
    <!-- 服务端模板直接输出初始CSV内容 -->
    <?!= testCSV2() ?>
  </body>
  <script>
    function getCsvContent() {
      // 异步调用服务端函数,通过回调接收返回结果
      google.script.run
        .withSuccessHandler(function(res) {
          document.getElementById("contentArea").innerText = res;
        })
        .withFailureHandler(function(err) {
          console.error("执行报错:", err);
        })
        .testCSV2();
    }
  </script>
</html>
调试提示
  • 改完代码后一定要刷新浏览器中的表格页面,重新触发授权,再打开侧边栏才会加载最新代码,否则会一直运行旧版本缓存
  • 代码中新增了withFailureHandler回调,打开浏览器开发者工具的Console面板就能看到服务端的执行报错,方便排查问题
  • 模板语法不要写错标记,标准输出格式为<?!= 要输出的服务端返回值 ?>,字符写错就会被当成普通文本输出

侧边栏实际运行效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 20:31:11