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

如何编写Google Sheets脚本为目标范围匹配源范围的词语加粗

Google Sheets 匹配关键词批量加粗脚本实现

实现效果

  • 目标处理范围:A列所有非空单元格
  • 关键词来源:B列所有非空单元格内容
  • 匹配规则:不区分大小写,支持子串匹配
  • 最终效果:A列单元格中所有和B列关键词匹配的字符片段自动设置为加粗格式

完整脚本代码

function boldMatchedSubstrings() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  // 读取B列所有非空关键词并去重
  const keywords = sheet.getRange("B:B").getValues()
    .flat()
    .filter(item => item && item.toString().trim() !== "")
    .map(item => item.toString().trim())
    .filter((item, index, arr) => arr.indexOf(item) === index);
  
  if (keywords.length === 0) return;

  // 转义关键词中的正则特殊字符,构造不区分大小写的全局匹配规则
  const escapedKeywords = keywords.map(k => k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
  const matchRegex = new RegExp(escapedKeywords.join('|'), 'gi');

  // 读取A列所有内容批量处理富文本格式
  const columnARange = sheet.getRange("A:A");
  const columnAValues = columnARange.getValues();
  const richTextResult = columnAValues.map(row => {
    const text = row[0]?.toString() || "";
    if (!text) return [SpreadsheetApp.newRichTextValue().setText("").build()];
    
    const richTextBuilder = SpreadsheetApp.newRichTextValue().setText(text);
    const boldStyle = SpreadsheetApp.newTextStyle().setBold(true).build();
    let matchResult;
    // 遍历所有匹配位置设置加粗样式
    while ((matchResult = matchRegex.exec(text)) !== null) {
      richTextBuilder.setTextStyle(matchResult.index, matchResult.index + matchResult[0].length, boldStyle);
    }
    return [richTextBuilder.build()];
  });

  // 批量写入处理后的格式,避免逐单元格操作卡顿
  columnARange.setRichTextValues(richTextResult);
}

使用步骤

  • 打开需要处理的Google Sheets表格,点击顶部菜单栏 扩展程序 > Apps 脚本 进入脚本编辑器
  • 删除编辑器默认生成的空白代码,将上述完整代码粘贴后点击保存,自定义项目名称即可
  • 首次运行需要完成权限验证,按照页面提示完成授权即可正常使用
  • 后续可以直接在脚本编辑器点击运行按钮触发功能,也可以根据需要自行添加自定义菜单在表格页直接触发

注意事项

  • 脚本自动转义了正则特殊字符,B列关键词包含*、$、.这类特殊符号也可以正常匹配
  • B列不要保留无关非空内容,避免出现误匹配
  • 单次运行支持处理万级行数据,超大表格可以自行修改范围参数优化运行速度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 06:06:01