Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 'For Loop' through Google Documents table

I have a table in a Google Document (Not Sheet). The first column contains an ID number which is a match to its relative ID in the Google Sheet that the Data was submitted from.

//This is what the table looks like
//[id][name][favourite cheese]
//[3 ][bob ][chedder]
//[4 ][jane][old english]

I need to

  1. Loop through each row in the Google DOCUMENT table.
  2. Identify if the cell in the first column contains 'text' (Identical to ID number)
  3. If it contains the text update the row with new data

Here is my current code:

// Grab the Table
var body = DocumentApp.openById('theId').getBody(),
  searchElement = body.findElement(DocumentApp.ElementType.TABLE),
  element = searchElement.getElement(),
  table = element.asTable();

That section of code is utilized to grab the table since you can't name tables in Google Documents.

I am so surprised I cannot find more info. I'm doing my best to utilize the documentation and have a feeling I will be using a 'For Loop' to search each row but will I need to .getElement(row) to loop through? Could I use .findText() or would that bring up every part of the table that contains the text. Maybe I could loop the .getElement(row) and .findText() in the first column of each row somehow?

I know looping is a fairly basic Javascript concept it's just the Google Documents way of doing things is confusing me.

like image 535
Bjaeg Avatar asked May 22 '26 13:05

Bjaeg


1 Answers

You are correct, you can loop through the rows using a Javascript for loop.

for (var i = 0; i < table.getNumRows(); ++i) {
  var row = table.getRow(i);
  Logger.log(row.getText());
}

Once you have the row, you can work with it how you like, for example getting the text from the first cell: row.getCell(0).getText()

A string comparison in JavaScript can be a straightforward ===, and then you can edit the text of the cell you are targeting (in this example, second column):

if (row.getCell(0).getText() === id) {
  row.getCell(1).setText('foo');
}
like image 177
MatthewG Avatar answered May 24 '26 01:05

MatthewG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!