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

Google Apps Script中用<?= ?>传参时HtmlService无法运行问题

问题原因
  • 你在displayTableInHTML函数中完成模板变量finalAbs赋值后,没有调用模板的evaluate()方法生成合法的HTML输出对象,也没有返回/渲染该结果,导致服务端没有有效内容返回给前端。
  • 如果你将脚本部署为Web App使用,Web App要求默认的入口处理函数必须命名为doGet,否则访问时会找不到执行入口直接抛出错误。
解决方法

1. 修正Code.gs代码

根据你的使用场景选择对应写法:

场景1:部署为Web App访问

// Web App要求必须使用doGet作为入口函数
function doGet() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const absenteeismTab = ss.getSheetByName("EmailOutput");
  const absDetail = absenteeismTab.getRange(5,2,10000,6).getValues();
  const finalAbs = [];
  for (let x = 0; x < absDetail.length; x++) {
    if (absDetail[x][0].length !== 0){
      finalAbs.push(absDetail[x]);
    }
  };

  const htmlTemplate = HtmlService.createTemplateFromFile("index");
  htmlTemplate.finalAbs = finalAbs;
  // 渲染模板并返回HTML输出
  return htmlTemplate.evaluate();
}

场景2:在Google Sheets内打开侧边栏展示

function displayTableInHTML() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const absenteeismTab = ss.getSheetByName("EmailOutput");
  const absDetail = absenteeismTab.getRange(5,2,10000,6).getValues();
  const finalAbs = [];
  for (let x = 0; x < absDetail.length; x++) {
    if (absDetail[x][0].length !== 0){
      finalAbs.push(absDetail[x]);
    }
  };

  const htmlTemplate = HtmlService.createTemplateFromFile("index");
  htmlTemplate.finalAbs = finalAbs;
  // 渲染模板并配置侧边栏参数
  const htmlOutput = htmlTemplate.evaluate().setTitle("缺勤数据");
  // 唤起侧边栏
  SpreadsheetApp.getUi().showSidebar(htmlOutput);
}

2. 可选:优化HTML展示效果

你当前的HTML代码直接输出数组会展示为无格式的拼接字符串,若要以表格形式展示嵌套数组数据,可以调整index.html代码如下:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <style>
      table, th, td {
        border: 1px solid #ccc;
        border-collapse: collapse;
        padding: 6px 12px;
      }
    </style>
  </head>
  <body>
    <h1>缺勤数据列表</h1>
    <table>
      <? finalAbs.forEach(row => { ?>
        <tr>
          <? row.forEach(cell => { ?>
            <td><?= cell ?></td>
          <? }) ?>
        </tr>
      <? }) ?>
    </table>
  </body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 08:30:01