Rinzler21
Rinzler21

Reputation: 476

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)
}

Upvotes: 0

Views: 900

Answers (1)

Tanaike
Tanaike

Reputation: 201388

  • You want to copy a table in the source Document to the destination Document.
  • You want to achieve this using Google Apps Script.

In this answer, the following sample situation is used.

  • There are 2 Google Documens which are source Document and destination Document.
  • The table is put to the source Document.
  • The destination Document has a text of {{replace}} as the paragraph.
  • When the sample script is run, the table in the source Document is copied and pasted to the destination Document by replacing {{replace}} with the table.

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:

Upvotes: 1

Related Questions