Insert an element (table) to the cursor position

2019-07-21 02:19发布

I would like to create a new Table element with custom style and append it to the current cursor position in the document. I saw that it is possible to get the current position with:

var cursor = DocumentApp.getActiveDocument().getCursor();

that returns a Position object. Position class provides a method to append Text to the current position:

cursor.insertText('ಠ‿ಠ');

but from the documentation I can't see a way to insert a generic Element (a Table in my case) instead of simple text.

On the other hand there is a method of the class Body that allows to append a Table to the end of the document, but it is not possible to specify a custom position.

Somebody can help?

Thanks

2条回答
老娘就宠你
2楼-- · 2019-07-21 02:50

Insert a STUB on it, eg. cursor.insertText('%%MY_TABLE_WILL_GO_HERE%%');, then continue the function to find this line and place the table.

查看更多
对你真心纯属浪费
3楼-- · 2019-07-21 02:53

Here's how I've pieced it together. I have a function createComponentTable that takes a boolean atCursor, which if false appends a table at the end of the document, and if true inserts a table at the cursor position.

(I also have a function doAlert(text) elsewhere that I can turn on/off for debugging.)

function createComponentTable(atCursor) {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var thisTable;

  if (atCursor) {
    var cursor = doc.getCursor();
    if (cursor) {
      var element = cursor.getElement();
      if (element) {
        var parent = element.getParent();
        thisTable = body.insertTable(parent.getChildIndex(element) + 1);
      } else {
        doAlert('Cannot insert there');
      }
    } else {
      doAlert('Could not get cursor position');
    }
  } else {
    thisTable = body.appendTable();
  }

  if (thisTable) {
    // add rows and cells to thisTable here
  }
}
查看更多
登录 后发表回答