1

Hoping I can get some advice on this. I'm using scripts to automate the creation of a document, where the data comes from an existing google doc. After no luck using linked tables, I'm trying to insert a table at a point identified by search text in the document.

For example, I'd search for TABLE1HERE in the document and replace it with a table defined by [[Heading,Data],[Heading2,MoreData]]. I've tried the below code and a number of variations with no luck. Any pointers would be fantastic.

function updateTablesTEST(searchText,replacementTable){

  var document = DocumentApp.getActiveDocument();
  var documentBody = document.getBody();
  var textLocation;
  var newPosition;
  var textChild;

  textLocation = documentBody.findText(searchText).getElement();
  textChild = textLocation.getParent().getChildIndex(textLocation);
  documentBody.insertTable(textChild+1, replacementTable);

}
healey
  • 314
  • 1
  • 12
  • 1
    Can I ask you about your question? 1. How is the text of ``TABLE1HERE`` putting in Document? For example, if this is putting in a table, it is required to modify the script for the situation. Can you provide a sample Document you want? 2. Can I ask you about the detail information of ``I've tried the below code and a number of variations with no luck.``? I think that providing such information will help users think of your issue. – Tanaike Feb 03 '19 at 04:00

1 Answers1

5

Replace Text with Table

This finds the childIndex of the container that contains the required text. It deletes the text and inserts a table into the same child.

function searchTextReplTable(texttofind){
  var doc=DocumentApp.getActiveDocument();
  var body=doc.getBody();
  var rgel=body.findText(texttofind);
  var element=rgel.getElement();
  var childIndex=body.getChildIndex(element.getParent());
  var t=[];//This is the table I used
  for(var i=0;i<5;i++){//just created a 5,5 table with row, col indices
    t[i]=[];
    for(var j=0;j<5;j++){
      t[i][j]=Utilities.formatString('%s,%s',i,j);
    }
  }
  body.getChild(childIndex).asText().setText('');
  body.insertTable(childIndex,t)
}
Cooper
  • 59,616
  • 6
  • 23
  • 54
  • Thanks for this, I used this as the basis of my code and it works perfectly. Thanks very much! – healey Feb 05 '19 at 21:58
  • I haven't look at it yet but they just released the Google Docs Rest API [here](https://developers.google.com/docs/api/) – Cooper Feb 05 '19 at 23:00