Google 脚本 - getNumCells Return 值(获取每行中的列数)

Google Scripts - getNumCells Return Value (get number of columns in each row)

在这个基本示例中,我试图查看在 google 文档中找到的 table 的每一行中有多少列。

  tables.forEach(function(table) {
  var numberOfRows = table.getNumRows();
  console.log("New Table with Rows: " + numberOfRows);
  for (var rowIndex = 0; rowIndex < numberOfRows; rowIndex++) {
    var row = table.getRow(rowIndex);
    console.log("row: " + rowIndex + " with num of cells: " + row.getNumCells());
  }
  })

这是我的 table 作为测试的样子。

这是我截取的代码的输出

New Table with Rows: 6
row: 0 with num of cells: 4
row: 1 with num of cells: 4
row: 2 with num of cells: 4
row: 3 with num of cells: 4
row: 4 with num of cells: 4
row: 5 with num of cells: 4

我期望它输出的单元格数量是每个特定行中的列数。我错过了什么?似乎getNumCells returns整个table的最大列数。如何计算每行中有多少列?

你的情况,用ClassTableCell的getColSpan()方法怎么样?当这反映到您的脚本中时,它会变成如下。

修改后的脚本:

tables.forEach(function(table) {
  var numberOfRows = table.getNumRows();
  console.log("New Table with Rows: " + numberOfRows);
  for (var rowIndex = 0; rowIndex < numberOfRows; rowIndex++) {
    var row = table.getRow(rowIndex);
    var nCol = 0;
    for (var colIndex = 0; colIndex < row.getNumCells(); colIndex++) {
      nCol += row.getCell(colIndex).getColSpan() == 0 ? 0 : 1;
    }
    console.log("row: " + rowIndex + " with num of cells: " + nCol);
  }
});

参考: