google-apps-scriptgoogle-docs

Copy a specific table and paste it in a specific part of a doc


I'm trying to copy a table that i already have in my doc and paste it in other part of the doc, someone know how to do that?

I'm very new doing this so what i have until now is to copy some table and paste it randomly. I want to copy the table i want not some table and paste it wherever i want not randomly

*Here is the link to my doc * https://docs.google.com/document/d/1s2TCspXbjvHVurwhIWSdwJ_hMcZIoLTKj4FAB82nmhM/edit?usp=sharing

Here is my current code

function copyBody(){
  var sourcedoc = DocumentApp.openById('1nH84jfwW0-YD4_6LgRQF7MXB7GsWeTomAQK1Foz3BLE');
  var sourcebody = sourcedoc.getBody();
  var tables = sourcebody.getTables();
  var table = tables[0].copy();
  var x = sourcebody.appendTable(table)
}

Solution

  • In this answer, the following sample situation is used.

    Sample script:

    Before you run the script, please copy and paste {{replace}} to the destination Document. And then, please run the script.

    function myFunction() {
      const sourceDocId = "###";  // Please set the source Document ID.
      const destinationDocId = "###";  // Please set the destination Document ID.
    
      const srcDoc = DocumentApp.openById(sourceDocId);
      const srcTable = srcDoc.getBody().getTables()[0].copy();
    
      const dstDoc = DocumentApp.openById(destinationDocId);
      const dstBody = dstDoc.getBody();
      const find = dstBody.findText("{{replace}}");
      if (find) {
        const child = find.getElement().getParent();
        const childIndex = dstBody.getChildIndex(child);
        dstBody.insertTable(childIndex, srcTable);
        find.getElement().removeFromParent();  // <--- Modified
      }
    }
    

    References: