1

I am trying to modify a google document table that has multiple rows, but each row has different number of columns.

Here is an example table enter image description here

How do I use table.getCell(row,col) or row.getCell(col) to get the contents of a,b,c,d,e,f,g etc..

What is the proper way to address each cell and modify the contents. The tables I am dealing with have a defined structure.

  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);
      // this is a table of interest and we know the exact structure
      if(rowIndex == 0 && row.getCell(0).getText().toString().trim().includes("2 cols")){
        row.getCell(0).editAsText().setText("11");
        row.getCell(1).editAsText().setText("12");
      }else if(rowIndex == 1 && row.getCell(0).getText().toString().trim().includes("3 cols")){
        row.getCell(1).editAsText().setText("21");
        row.getCell(2).editAsText().setText("22");
      }else if(rowIndex == 2 && row.getCell(0).getText().toString().trim().includes("5 cols")){
          row.getCell(1).editAsText().setText("31");
          row.getCell(2).editAsText().setText("32");  // NOTE1: THIS IS THE ISSUE
          row.getCell(3).editAsText().setText("33");  // NOTE3: THIS IS THE ISSUE
      }
    }
  })

Here is the table output of the code above enter image description here

How come NOTE1 and NOTE2 did not modify cells e, and cells f?

1 Answer 1

0

I thought that in your script, the values of getColSpan() of row.getCell(1), row.getCell(2) and row.getCell(3) are 3, 0 and 0, respectively. When the value of getColSpan() is 0, it means the merged cell. I thought that this might be the reason for your issue. So, in order to achieve your goal, how about the following modification?

From:

row.getCell(1).editAsText().setText("31");
row.getCell(2).editAsText().setText("32");  // NOTE1: THIS IS THE ISSUE
row.getCell(3).editAsText().setText("33");  // NOTE3: THIS IS THE ISSUE

To:

var nCol = 0;
var values = ["31", "32", "33"];
for (var colIndex = 1; colIndex < row.getNumCells(); colIndex++) {
  var cell = row.getCell(colIndex);
  if (values.length > nCol && cell.getColSpan() > 0) {
    cell.editAsText().setText(values[nCol++]);
  }
}
  • By this modification, the row of 5 cols has the values of 5 cols, 31, 32, 33.
Sign up to request clarification or add additional context in comments.

2 Comments

Resolved! Thank you. Not sure why I am struggling with these tables. You are helping out very much.
@Sliffcak Thank you for replying. I'm glad your issue was resolved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.