Pergunta

Is it possible to append a table after a selection in Google Document using Apps Script?

Only example I can find is this:

var body = DocumentApp.getActiveDocument().getBody();
var table = body.appendTable();

...which means to the end of document.

Thanks
EDIT:

How I make selection is:

var selection = doc.getSelection();

which is basicaly what is selected by mouse drag selection (blued out) on document editor.
From there I start to iterrate:

var elements = selection.getSelectedElements();  
var element = elements[0].getElement();
var startOffset = elements[0].getStartOffset();      // -1 if whole element  
var endOffset = elements[0].getEndOffsetInclusive(); // -1 if whole element 

This might be a part of PARAGRAPH.

Foi útil?

Solução

Here is code that inserts a table at the current selection. It may need to be modified a little, but the point is; that it finds the child index of the body at the point of the selection.

function insertTableAtSelection() {
  // insert table as selection
  var theDoc = DocumentApp.getActiveDocument();
  var selection = theDoc.getSelection();
  Logger.log('selection: ' + selection);

  if (selection) {
    var elements = selection.getRangeElements();
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      Logger.log('element: ' + element.getElement());
    };

    var theElmt = element;
    var selectedElmt = theElmt.getElement();
    Logger.log('selectedElmt: ' + selectedElmt);

    var parent = selectedElmt.getParent();

    var insertPoint = parent.getChildIndex(selectedElmt);
    Logger.log('insertPoint: ' + insertPoint);    

    var body = theDoc.getBody();
    var table = body.insertTable(insertPoint + 1, [['one','two','three'],['yellow', 'green', 'red']]);
  };
};

The insertPoint is increased by one:

insertPoint + 1

That gets the table just beyond the selection.

For anyone reading this post who may want to adapt this code, keep in mind that this code only completes if there is a selection; the user needs to have highlighted some amount of content for there to be a selection.

Outras dicas

You can append a table anywhere in the document, you only need to get the container element of your search result and append the table to it.

Have a look at this post for example to see how documents are build (but there are more... search on this forum with Google-Apps-Script tag.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top