Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading