Get Table Cell Values Google Docs

2019-06-12 23:54发布

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']

1条回答
Fickle 薄情
2楼-- · 2019-06-13 00:42

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
查看更多
登录 后发表回答