2

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

tano
  • 836
  • 1
  • 10
  • 25
  • Did you get some workaround? – RAJ Dec 15 '15 at 18:11
  • 1
    I posted an answer to a [duplicate question of this one](http://stackoverflow.com/questions/33945638/insert-a-table-into-google-doc-at-cursor-position/40675038#40675038) – Yuval Nov 18 '16 at 10:44

2 Answers2

1

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
  }
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
axemonkey
  • 43
  • 4
0

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.

Kriggs
  • 3,731
  • 1
  • 15
  • 23