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

Google Apps Script 生成邮件HTML表格按条件修改文本颜色问题问询

实现方案

绝大多数邮件客户端会自动拦截HTML邮件内的JavaScript代码,因此你原有模板里写的变色JS逻辑无法生效,直接在Apps Script模板渲染阶段通过条件判断添加内联样式即可实现需求,不需要修改原有的.gs业务逻辑代码。

修改邮件HTML模板

调整循环渲染行的第8个单元格(对应r[7]字段)的代码,同时删除无用的JS代码即可,修改后的完整模板代码如下:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <style>
  table, th, td {
  border: 0px solid black;
  font-size:15px;
}

th, thead {
  background-color: lightblue;
}

</style>  
  </head>
  <body>
    <div>
      <table id="table1">
        <thead>
          <th><?= hospital ?></th><th><?= asset ?></th><th><?= time ?></th><th><?= helevel ?></th><th><?= hepressure ?></th><th><?= chillertemp ?></th><th><?= roomtemp ?></th><th><?= compressor ?></th>
        </thead>
        <tbody >
          <? tablerangeValue.forEach(r => {?>
          <tr> 
          <td><?= r[0] ?></td><td><?= r[1] ?></td><td><?= r[2] ?></td><td style="text-align:center"><?= r[3] ?></td><td style="text-align:center"><?= r[4] ?></td><td style="text-align:center"><?= r[5] ?></td><td style="text-align:center"><?= r[6] ?></td>
          <!-- 下方为修改后的r[7]对应单元格,判断值为FAULT时加红色样式 -->
          <td style="text-align:center; <?= r[7] === 'FAULT' ? 'color: red;' : '' ?>" ><?= r[7] ?></td>
          </tr>
          <?})?>
          
        </tbody>

      </table>
    </div>
  </body>
  
</html>

可选拓展:同步修改Google Sheet原表对应单元格颜色

如果需要在发送邮件的同时,把Google Sheet原表里状态为FAULT的单元格文本也改为红色,可以在.gs业务代码的const tablerangeValue = ws.getRange(2,1,18,9).getDisplayValues()这一行之后,加入以下代码:

// 同步修改原表H列FAULT单元格的文本颜色
const statusColumnRange = ws.getRange(2, 8, 18, 1); // 匹配你取数的H列2到19行范围
const statusValues = statusColumnRange.getDisplayValues();
const styleArr = statusValues.map(row => {
  return [row[0] === 'FAULT' ? SpreadsheetApp.newTextStyle().setForegroundColor('red').build() : null]
});
statusColumnRange.setTextStyles(styleArr);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:36:04