How to get selected table in Google apps script

2019-08-19 16:11发布

I am writing a script that will use a table that a user has selected. However, using DocumentApp.getActiveDocument().getSelection().getRangeElements() will get only the individual cells. I thought I could just reconstruct the table, but the cells are all in one long list with no info on rows or columns, and the user should be able to select a table of any height/width without having to tell the program what the dimensions are. I also thought about having the program automatically select a bit ahead, in order to treat the table as a table and not individual cells, but this still selects individual cells (but not all of them which is a bit peculiar.) Thanks for any feedback/help!

1条回答
我命由我不由天
2楼-- · 2019-08-19 16:19

Replacing a table selected by placing cursor in any cell

I just made up a two dimensional array for the table to be replaced with.

If you try to cast the first element asTable() you'll get the error 'PARAGRAPH can't be cast to TABLE.' then if add another getParent() you'll get the error 'TABLE_CELL can't be cast to TABLE. ' and then add another getParent() and you'll get the error 'TABLE_ROW can't be cast to TABLE.' and finally adding yet another getParent() finally passes through the gauntlet and replaces the the table. You can put the cursor in any cell in the table. It was a bit of a hack but in the end it seems to work. It would have been much more difficult to figure this out without knowing how to use the debug resources that Google provides.

function replaceTableAtCursor(){
  var doc=DocumentApp.getActiveDocument();
  var body=doc.getBody();
  var el=doc.getCursor().getElement().getParent().getParent().getParent();//element/cell/row/table
  var table=el.asTable();
  var t=[];//This is the table I used. Any 2D array will work like the ones you can get from getValues() method from spreadsheets.
  for(var i=0;i<3;i++){
    t[i]=[];
    for(var j=0;j<3;j++){
      t[i][j]=Utilities.formatString('i:%s,j:%s',i,j);
    }
  }
  var childIndex=body.getChildIndex(el)
  table.clear();
  body.insertTable(childIndex,t)  
}
查看更多
登录 后发表回答