Get Table Cell Values Google Docs

六眼飞鱼酱① 提交于 2019-12-23 04:53:27

问题


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:

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:


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


来源:https://stackoverflow.com/questions/34857892/get-table-cell-values-google-docs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!