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

如何用Google Apps Script提取单元格指定行业词至另一列

Google Sheets 分离名称与行业名称的Apps Script实现

实现思路

  1. 从指定列提取所有行业名称,构建匹配字典,优先匹配较长的行业名称(避免短名称误匹配)
  2. 遍历目标列的每一行字符串,查找其中包含的行业名称
  3. 将找到的行业名称写入相邻列,同时把原字符串去掉行业名称后的纯名称存入对应列

完整代码

function splitNameAndIndustry() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  // 可根据你的实际列位置修改参数:列号从1开始计数
  const targetCol = 1; // 存放名称+行业组合字符串的列(示例为A列)
  const industryCol = 2; // 存放行业名称字典的列(示例为B列)
  const resultCol = 3; // 输出提取出的行业名称的列(示例为C列)
  const nameResultCol = 4; // 输出分离后纯名称的列(示例为D列,可选)

  // 处理行业列数据:去重、过滤空值、按长度倒序排序(优先匹配长行业名)
  const industryRange = sheet.getRange(2, industryCol, sheet.getLastRow() - 1);
  const industryList = industryRange.getValues().flat()
    .filter(item => item.toString().trim() !== "")
    .filter((value, index, self) => self.indexOf(value) === index)
    .sort((a, b) => b.length - a.length);

  // 获取目标列的所有数据
  const targetRange = sheet.getRange(2, targetCol, sheet.getLastRow() - 1);
  const targetValues = targetRange.getValues();

  // 准备结果数组
  const industryResults = [];
  const nameResults = [];

  // 遍历每一行进行匹配拆分
  targetValues.forEach(row => {
    const originalStr = row[0].toString().trim();
    let matchedIndustry = "";
    let pureName = originalStr;

    // 逐个匹配行业名称,找到即停止
    for (const industry of industryList) {
      const industryStr = industry.toString().trim();
      if (originalStr.includes(industryStr)) {
        matchedIndustry = industryStr;
        pureName = originalStr.replace(industryStr, "").trim();
        break;
      }
    }

    industryResults.push([matchedIndustry]);
    nameResults.push([pureName]);
  });

  // 将结果写入表格
  sheet.getRange(2, resultCol, industryResults.length, 1).setValues(industryResults);
  sheet.getRange(2, nameResultCol, nameResults.length, 1).setValues(nameResults);
}

使用步骤

  1. 打开你的Google Sheets文档
  2. 点击顶部菜单栏扩展程序 > Apps 脚本
  3. 删除编辑器里默认的myFunction代码,粘贴上述完整代码
  4. 根据你的表格实际列布局,修改代码开头的列号参数
  5. 点击脚本编辑器顶部的运行按钮,首次运行需按提示完成授权
  6. 返回表格刷新,即可看到分离后的结果

注意事项

  • 行业列的空行、重复行业名称会被自动过滤
  • 优先匹配较长的行业名称,避免类似"科技"和"信息技术科技"的误匹配
  • 若某一行的组合字符串无匹配行业,结果列会留空

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 15:27:09