1

We have a Google Document with a Table init, where we need to get the values inside the table cells into an Array. The table looks like this in Google Doc: enter image description here

I found a way to logg the values in the cells with this code:

 var searchElement = copyBody.findElement(DocumentApp.ElementType.TABLE);
     var element = searchElement.getElement();
     var table = element.asTable();
     var tablerows = element.getNumRows();

        for ( var row = 0; row < tablerows; ++row ) {
          var tablerow = element.getRow(row)
          for ( var cell=0; cell < tablerow.getNumCells(); ++cell) {


            var celltext = tablerow.getChild(cell).getText();
           Logger.log( "Text is ("+celltext+")" );

          }
        }

How can we get these into an array that looks something like this:

   ['A', 'C', 'E', 'X'],
   ['Row 2, Cell 1 value', 'Row 2, Cell 2 value', 'Row 2, Cell 3 value', 'Row 2, Cell 4 value'],
   ['Row 3, Cell 1 value', 'Row 3, Cell 2 value', 'Row 3, Cell 3 value', 'Row 3, Cell 4 value']
John Smith
  • 387
  • 2
  • 8
  • 24
  • I think we found something to 'search' for the Table in the document, we need to search for an Element, and that Element is 'Table'. But still can't figure it out. https://developers.google.com/apps-script/reference/document/table#findelementelementtype – John Smith Jan 18 '16 at 15:42

1 Answers1

3

You seem to be 90% the way there. If all you really want to do is get those cells into an array I'm surprised you can't make the next step? Allow me:

var array = [];
for ( var row = 0; row < tablerows; ++row ) {
  var tablerow = element.getRow(row)
  array[row] = [];
  for ( var cell=0; cell < tablerow.getNumCells(); ++cell) {
    var celltext = tablerow.getChild(cell).getText();
    array[row][cell] = celltext;
  }
}
Logger.log(JSON.stringify(array)); // debug
DDD
  • 1,462
  • 15
  • 19