Referencing cells in tables on a Google Doc

2019-08-18 03:14发布

I'm trying to automatically format a table in a Google Doc cell by cell. Once I have a table stored in the variable table, I try to use getCell to reference the cell in the top left of this table, but it doesn't return the cell I'm after.

I noticed that in the Google Scripts reference, they note that to point to a cell, the correct usage is getCell(rowIndex, cellIndex). What does cellIndex refer to in this case, and does it relate to some sort of columnIndex?

Any pointers on this would be appreciated.

2条回答
该账号已被封号
2楼-- · 2019-08-18 03:52

Editing a table in a Google Doc

Here's an example that edits all of the cell contents of a table selected by placing the cursor inside one of it's cells.

rowIndex goes from 0 to table.getNumRows()-1;

cellIndex goes from 0 to table.getRow(i).getNumCells()-1

function editTableAtCursor(){
  var doc=DocumentApp.getActiveDocument();
  var el=doc.getCursor().getElement().getParent().getParent().getParent();
  var table=el.asTable();
  var rows=table.getNumRows();
  for(var i=0;i<table.getNumRows();i++) {
    for(var j=0;j<table.getRow(i).getNumCells();j++) {
      table.getCell(i,j).editAsText().setText(Utilities.formatString('Row: %s Cell: %s',i,j));
    }
  }
}
查看更多
够拽才男人
3楼-- · 2019-08-18 04:09

Yes, the cellIndex refers to columnIndex. Consider the below example

    function getCellVal() {

  var docBody=DocumentApp.getActiveDocument().getBody();
  var table=docBody.getTables()[0];
  Logger.log(table.getCell(0,0).getText())

}

Here, the value in Logger will retrieve the cell value in first row and first column of the table. the index for row and column starts from 0.

Hope this helps!.

查看更多
登录 后发表回答