繁体   English   中英

将多个选项卡(按列,而不是逐行)合并到 Google 表格中的主表格中

[英]Merge multiple tabs (Column wise, not row by row) into a master sheet in google sheets

我正在尝试将存储在多个选项卡中的信息合并到一个主表中,使其在此示例表中看起来像“最终”。 我在网上找到了一个代码,它做了类似的事情,但按行合并信息,这对我来说并不理想。 代码如下所示:

 function merge() { const ss = SpreadsheetApp.getActive(); const arr = ss .getSheets() .filter(s => !s.getName().includes('Master'))//exclude Master sheet .flatMap(s => s.getDataRange().getValues());//map sheet to values and flatten it ss.getSheetByName('Master') .getRange(1, 1, arr.length, arr[0].length) .setValues(arr); }

如果您有任何建议,请告诉我。 提前致谢。

问题:

每个工作表的值作为目标工作表中的连续行附加。 那是因为外部数组对应于行。

您应该将每个工作表行的值添加到每个内部数组。 那将对应于列。

解决方案:

转置数组,使列对应于外部数组,然后转回。

此外,由于所有工作表中的第一列都相同,因此您只想为第一列复制它,因此在使用flatMap时应检查索引,并且在这些情况下不要通过getDataRange检索完整范围(使用getRange代替) .

代码示例:

function merge() {
  const ss = SpreadsheetApp.getActive();
  const excludedSheetNames = ['Master', 'Final']; // Add excluded sheet names
  let arr = ss
    .getSheets()
    .filter(s => !excludedSheetNames.includes(s.getName()); //exclude several sheets
    .flatMap((s, i) => {
      let values;
      if (i === 0) values = s.getDataRange().getValues();
      else values = s.getRange(1,2,s.getLastRow(),s.getLastColumn()-1).getValues(); // Ignore first column for non-first sheet
      values = values[0].map((_, colIndex) => values.map(row => row[colIndex])); // Transpose 2D array
      return values;
    });
  arr = arr[0].map((_, colIndex) => arr.map(row => row[colIndex])); // Transpose back
  ss.getSheetByName('Master')
    .getRange(1, 1, arr.length, arr[0].length)
    .setValues(arr);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM