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

如何使用Google Apps Script合并A列值相同的Google Sheets行

Google Sheets 客户采购行自动合并方案

操作步骤

  • 打开目标Google Sheets表格,点击顶部菜单栏「扩展程序」>「Apps Script」进入脚本编辑器
  • 删除编辑器内默认的空白代码,粘贴下方的完整脚本
  • 点击保存按钮,自定义项目名称(例如「客户数据合并工具」),按照页面提示完成脚本访问表格的权限授权
  • 回到Google Sheets页面刷新,顶部会新增「自定义工具」菜单,点击菜单内的「合并相同客户行」即可一键完成合并

完整脚本代码

// 初始化自定义菜单,打开表格时自动加载
function onOpen() {
  const ui = SpreadsheetApp.getUi();
  ui.createMenu('自定义工具')
    .addItem('合并相同客户行', 'mergeCustomerRows')
    .addToUi();
}

function mergeCustomerRows() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const allData = sheet.getDataRange().getValues();
  // 提取表头,不参与合并逻辑
  const headerRow = allData.shift();
  const customerDataMap = new Map();

  // 遍历所有数据行做合并
  allData.forEach(currentRow => {
    const customerName = currentRow[0];
    // 跳过客户名称为空的行
    if (!customerName) return;

    if (customerDataMap.has(customerName)) {
      const existedRow = customerDataMap.get(customerName);
      // 从第二列开始合并,空值位置用当前行的非空值填充
      for (let colIndex = 1; colIndex < currentRow.length; colIndex++) {
        if (!existedRow[colIndex] && existedRow[colIndex] !== 0) {
          existedRow[colIndex] = currentRow[colIndex];
        }
      }
      customerDataMap.set(customerName, existedRow);
    } else {
      customerDataMap.set(customerName, currentRow);
    }
  });

  // 组装最终输出数据
  const resultData = [headerRow, ...Array.from(customerDataMap.values())];
  // 清空原有内容后写入新数据
  sheet.clearContents();
  sheet.getRange(1, 1, resultData.length, resultData[0].length).setValues(resultData);
}

功能说明

  • 默认保留第一行表头不处理,适配你表格的结构
  • 合并规则:相同客户名称的行,同一列优先保留非空值,完美匹配1-3月、4-9月数据分两行存储的场景
  • 仅修改单元格内容,不会改动你提前设置好的单元格格式、数据验证规则等配置

注意事项

  • 首次运行脚本需要授权,遇到Google安全提示时,点击「高级」>「前往[你的项目名](不安全)」即可继续授权,个人开发的脚本不会泄露你的数据
  • 建议首次使用前先备份原始数据,避免误操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 21:54:02