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

能否用Google Apps Script重构表格数据适配Google Combo Bar Chart?

Google Apps Script 实现表格数据重构(适配组合条形图)

需求说明

将包含Titles、Languages、Copies三列的源数据,转换为以语言为列标题的宽表格式——每行对应一个Title,各语言列填充对应的Copies数值,以此适配Google Combo Bar Chart的创建需求。

实现脚本

function restructureData() {
  // 替换为你的源工作表和目标工作表名称
  const sourceSheetName = "源数据";
  const targetSheetName = "重构后数据";
  
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sourceSheet = ss.getSheetByName(sourceSheetName);
  const targetSheet = ss.getSheetByName(targetSheetName) || ss.insertSheet(targetSheetName);
  
  // 获取源数据(包含表头)
  const sourceData = sourceSheet.getDataRange().getValues();
  if (sourceData.length <= 1) return; // 无数据则直接退出
  
  // 定位各列索引
  const [header, ...rows] = sourceData;
  const titleColIndex = header.indexOf("Titles");
  const langColIndex = header.indexOf("Languages");
  const copiesColIndex = header.indexOf("Copies");
  
  // 提取所有唯一语言,作为新表头的组成部分
  const uniqueLangs = [...new Set(rows.map(row => row[langColIndex]))].filter(Boolean);
  // 构建新表头:Titles + 所有语言
  const newHeader = ["Titles", ...uniqueLangs];
  
  // 建立标题到「语言-拷贝数」的映射关系
  const titleMap = new Map();
  rows.forEach(row => {
    const title = row[titleColIndex];
    const lang = row[langColIndex];
    const copies = row[copiesColIndex] || 0;
    
    if (!titleMap.has(title)) {
      titleMap.set(title, new Map());
    }
    titleMap.get(title).set(lang, copies);
  });
  
  // 生成目标数据行
  const targetRows = Array.from(titleMap.entries()).map(([title, langMap]) => {
    const row = [title];
    uniqueLangs.forEach(lang => {
      row.push(langMap.get(lang) || 0);
    });
    return row;
  });
  
  // 写入数据到目标工作表
  targetSheet.clear();
  targetSheet.getRange(1, 1, 1, newHeader.length).setValues([newHeader]);
  targetSheet.getRange(2, 1, targetRows.length, newHeader.length).setValues(targetRows);
  
  // 自动调整列宽
  targetSheet.autoResizeColumns(1, newHeader.length);
}

使用步骤

  1. 打开目标Google表格,点击顶部菜单栏工具 > 脚本编辑器
  2. 将上述代码粘贴到编辑器中,修改sourceSheetName和targetSheetName为你实际的工作表名称
  3. 点击编辑器顶部的运行按钮,首次运行需授权脚本访问表格数据
  4. 授权完成后再次运行,目标工作表会自动生成重构后的宽表数据

可选调整

  • 若同一标题对应同一语言有多条数据,需要求和的话,可将titleMap.get(title).set(lang, copies)改为titleMap.get(title).set(lang, (langMap.get(lang) || 0) + copies)
  • 若源表头字段名不同,需同步修改代码中列索引定位的匹配值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 19:15:05