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

如何用Google Apps Script查找邮件正文中匹配的表格时间戳并返回行号

解决方案

步骤1:从邮件正文提取时间戳

邮件正文包含时间戳和其他内容,需要先把时间戳单独提取出来。假设时间戳格式为MM/DD/YYYY HH:MM:SS,用正则匹配提取:

// 提取邮件中的时间戳,可根据实际格式调整正则表达式
const timestampRegex = /\d{1,2}\/\d{1,2}\/\d{4} \d{1,2}:\d{2}:\d{2}/;
const match = approvedeny.match(timestampRegex);
if (!match) {
  Logger.log("未在邮件中找到时间戳");
  return;
}
const targetTimestamp = match[0];

步骤2:遍历表格时间戳列查找匹配行号

表格中的时间戳是Date对象,需转成和邮件一致的字符串格式再比较,同时获取对应行号:

// 获取时间戳列数据(假设在A列,可根据实际列调整)
const timestampColumn = sheet_apprdeny.getRange(1, 1, sheet_apprdeny.getLastRow(), 1).getValues();

// 遍历查找匹配项
for (let i = 0; i < timestampColumn.length; i++) {
  // 转换表格时间戳格式,时区需和表单提交时区一致
  const sheetTimestamp = Utilities.formatDate(timestampColumn[i][0], Session.getScriptTimeZone(), "MM/dd/yyyy HH:mm:ss");
  if (sheetTimestamp === targetTimestamp) {
    const rowNumber = i + 1; // 表格行号从1开始计数
    Logger.log("匹配的行号:" + rowNumber);
    // 可在此添加后续操作,比如更新该行数据
    return rowNumber;
  }
}

Logger.log("未找到匹配的时间戳");

完整整合代码

function updateSheetC() {
  // GMAIL QUERY
  const q = GmailApp.search('label:ProcessesTEST');
  if (q.length === 0) {
    Logger.log("未找到标记为ProcessesTEST的邮件");
    return;
  }

  const num = q[0].getMessageCount();
  const approvedeny = q[0].getMessages()[num - 1].getPlainBody();

  // 提取邮件中的时间戳
  const timestampRegex = /\d{1,2}\/\d{1,2}\/\d{4} \d{1,2}:\d{2}:\d{2}/;
  const match = approvedeny.match(timestampRegex);
  if (!match) {
    Logger.log("未在邮件中找到时间戳");
    return;
  }
  const targetTimestamp = match[0];

  // SHEET INFO
  const id = '1FEP50qGUJcS6FJJkcPwX1cclrnOJ5Y6iRjKOkzoWc4A';
  const spreadsheet = SpreadsheetApp.openById(id);
  const sheet_apprdeny = spreadsheet.getSheetByName('Form Responses 1');
  if (!sheet_apprdeny) {
    Logger.log("未找到名为Form Responses 1的工作表");
    return;
  }

  // 查找匹配的时间戳行号
  const timestampColumn = sheet_apprdeny.getRange(1, 1, sheet_apprdeny.getLastRow(), 1).getValues();
  for (let i = 0; i < timestampColumn.length; i++) {
    const sheetTimestamp = Utilities.formatDate(timestampColumn[i][0], Session.getScriptTimeZone(), "MM/dd/yyyy HH:mm:ss");
    if (sheetTimestamp === targetTimestamp) {
      const rowNumber = i + 1;
      Logger.log("匹配的行号:" + rowNumber);
      // 可添加后续业务逻辑
      return rowNumber;
    }
  }

  Logger.log("未找到匹配的时间戳");
}

注意事项

  • 正则表达式需根据邮件中时间戳的实际格式调整,比如格式为YYYY-MM-DD HH:MM:SS时,正则改为/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/。
  • 时间戳格式转换时,时区要和表单提交的时区保持一致,可替换Session.getScriptTimeZone()为具体时区,比如"GMT+8"。
  • 代码中添加了异常判断,避免无邮件、无工作表等场景导致脚本报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 11:42:51