使用 Google Apps 脚本删除幻灯片 table 底部的空合并行

Deleting empty merged rows at bottom of Slides table with Google Apps Script

我有一个 Google Apps 脚本,它从 Google Sheet 中获取数据并将其复制到带有 Table 的 Google 幻灯片模板中。在某些情况下,sheet 中的数据行不如模板 table 中的数据行多,因此 table 中的一些行部分留空(见屏幕截图table 下面)。我编写了一个函数,从 Google 幻灯片 table 中删除空行(请参阅下面的期望结果屏幕截图),并且它在其他没有任何合并单元格的 table 上运行良好(在 for 循环中使用 rowIndex++ 而不是 rowIndex = rowIndex + 3 的修改)。

function removeEmptyRowsTest(removeId) {
  var slides = SlidesApp.openById(removeId).getSlides();
  var metricExcepSlide = slides[0];
  var metricExcepTables = metricExcepSlide.getTables();
  var table = metricExcepTables[0];

  var numberOfRows = table.getNumRows(); 

  for (var rowIndex = 1; rowIndex < numberOfRows; rowIndex = rowIndex+3) {

    var nextRow = table.getRow(rowIndex);

    // A row is assumed empty until proven otherwise
    var foundEmptyRow = false;
    //Logger.log(numberOfColumns)
    Logger.log(foundEmptyRow)
    Logger.log(nextRow.getCell(0).getText().asString())
    Logger.log(nextRow.getCell(0).getText().asString().length)


    if (nextRow.getCell(0).getText().asString().length == 1) {
      foundEmptyRow = true;
    }


    if (foundEmptyRow) {
      table.getRow(rowIndex).remove()
      numberOfRows--;
      rowIndex--;
    }

  }
}

但是当我运行下图table上的函数时,我得到错误Exception: This operation is only allowed on the head (upper left) cell of the merged cells.。我很困惑,因为我觉得将 rowIndex 初始化为 1 并递增 3 应该只应用于三个合并单元格集合的左上角单元格。当我将 rowIndex 初始化为 0 and/or 并将其递增 1 时,我遇到了同样的错误。有人知道如何避免此错误并删除 table 底部的空行吗?

Link to sample google slides table

我相信你的目标如下。

  • 当 Google 幻灯片上的“A”、“C”、“D”和“E”列为空时,您想删除该行。
  • 您的目标显示在您问题的示例图片中。
  • 您想使用 Google Apps 脚本实现此目的。

这样的话,下面的修改怎么样?在这个修改中,使用getMergeState的方法检查“HEAD”和“MERGED”。使用反向循环。

修改后的脚本:

function removeEmptyRowsTest(removeId) {
  var slides = SlidesApp.openById(removeId).getSlides();
  var metricExcepSlide = slides[0];
  var metricExcepTables = metricExcepSlide.getTables();
  var table = metricExcepTables[0];
  var numberOfRows = table.getNumRows();

  // I modified below script.
  var checkCols = [0, 2, 3, 4];
  for (var r = numberOfRows - 1; r > 0; r--) {
    if (table.getRow(r).getCell(0).getMergeState() == SlidesApp.CellMergeState.HEAD) {
      var checkEmpty = checkCols.filter(e => table.getRow(r).getCell(e).getText().asString().trim() != "");
      if (checkEmpty.length == 0) {
        for (var dr = 3; dr > 0; dr--) {
          table.getRow(r + dr - 1).remove();
        }
      }
    }
  }
}
  • 当上面的脚本是 运行 时,Google 幻灯片上的 table 的“A”、“C”、“D”和“E”列被选中,并且当这些列为空值时,该行将被删除。

参考: