【问题标题】:Merge multiple tabs (Column wise, not row by row) into a master sheet in google sheets将多个选项卡(按列,而不是逐行)合并到谷歌工作表中的主工作表中
【发布时间】:2021-07-20 21:12:37
【问题描述】:

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

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);
}

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

【问题讨论】:

    标签: google-apps-script google-sheets google-sheets-formula


    【解决方案1】:

    问题:

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

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

    解决方案:

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

    另外,由于所有工作表中的第一列都是相同的,因此您只想将其复制到第一列,因此在使用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);
    }
    

    【讨论】:

    • 感谢您的详细解决方案。非常感激!当我在第 5 行使用“Master”时,此代码不起作用,但在我使用 final 时起作用。错误-异常:范围内的行数必须至少为 1。此外,我想从整体合并中排除几张工作表,例如同时排除最终工作表和主工作表。有什么建议么?提前致谢!
    • @MariaMasood 这可能意味着Master 表是空的,所以当尝试检索s.getRange(1,2,s.getLastRow(),s.getLastColumn()-1) 的范围时如果失败,因为getLastRow() 返回0。无论如何,我已经修改您可以排除多张工作表的脚本(在这种情况下为MasterFinal)。首先,排除工作表的数组被定义为` const excludeSheetNames = ['Master', 'Final'];, and then these sheets are filtered out .filter(s => !excludedSheetNames.includes(s.getName());`。我希望这很有用给你!
    • @MariaMasood 这个答案对您有用吗?如果是这种情况,请考虑接受stackoverflow.com/help/someone-answers
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多