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

如何在Apps Script中按特定条件拼接指定列内容生成数组

用Google Apps Script直接拼接表格指定列生成目标数组

实现思路

直接通过Apps Script读取表格数据,遍历每一行时完成以下操作:

  • 提取Option Name、Type 1、Type 2字段值
  • 优先选取Existing measure的内容,若为空则使用New measure
  • 按[Option Name]-C [Type X]-[时间周期]-[单位]的格式拼接字符串
  • 将所有行的拼接结果汇总到目标数组中

示例代码

function generateTargetArray() {
  // 获取当前活跃表格的工作表(可自行修改为指定工作表名称)
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  // 读取表格所有数据
  const data = sheet.getDataRange().getValues();
  // 配置各列的索引(根据你的表格实际列位置修改,示例假设:
  // Option Name=A列(0), Type 1=B列(1), Type 2=C列(2), Existing measure=D列(3), New measure=E列(4))
  const colIndexes = {
    optionName: 0,
    type1: 1,
    type2: 2,
    existingMeasure: 3,
    newMeasure: 4
  };

  const resultArray = [];

  // 跳过表头,从第2行开始遍历数据
  for (let i = 1; i < data.length; i++) {
    const row = data[i];
    const optionName = row[colIndexes.optionName];
    const type1 = row[colIndexes.type1];
    const type2 = row[colIndexes.type2];
    // 选取有值的measure字段
    const measure = row[colIndexes.existingMeasure] || row[colIndexes.newMeasure];

    // 跳过关键字段为空的无效行
    if (!optionName || (!type1 && !type2) || !measure) continue;

    // 拆分measure为时间周期和单位(假设格式为"Yearly-GB"这类)
    const [period, unit] = measure.split('-');

    // 分别处理Type1和Type2,生成对应拼接结果
    if (type1) {
      resultArray.push(`${optionName}-C ${type1}-${period}-${unit}`);
    }
    if (type2) {
      resultArray.push(`${optionName}-C ${type2}-${period}-${unit}`);
    }
  }

  // 输出结果到日志,也可根据需求返回或写入表格
  console.log(resultArray);
  return resultArray;
}

代码说明

  1. 列索引配置:根据你的表格实际列位置修改colIndexes中的数值(列索引从0开始计数)
  2. 空值过滤:自动跳过关键字段为空的行,避免生成无效字符串
  3. 格式适配:若Existing measure/New measure的格式不是[时间周期]-[单位],需调整split的拆分逻辑
  4. 多类型处理:每行的Type 1和Type 2会分别生成一条拼接结果,完全匹配你给出的示例格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 20:45:42