Search code examples
google-apps-scriptgoogle-docs

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


In this basic example I am trying to see how many columns are in each row in a table that is found in a google document.

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

Here is what my table looks like as a test. enter image description here

This is the output of my code snipped

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

I was expecting it to output num of cells to be the number of columns in each specific row. What am I missing? It seems getNumCells returns the max number of columns throughout the whole table. How do I figure out how many columns are in each row?


Solution

  • In your situation, how about using the method of getColSpan() of Class TableCell? When this is reflected to your script, it becomes as follows.

    Modified script:

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

    Reference: