Home > OS >  Table form spreadsheet to doc
Table form spreadsheet to doc

Time:11-30

I have a spreadsheet with cells avaliable for content in: A14:E. I have a doc template where I want to copy this table with the exact format. In spreadsheet I nameranged A14:E - "Tabel_angajati"

var ss = SpreadsheetApp.getActiveSpreadsheet();
var Tabel_angajati = ss.getRangeByName('Tabel_angajati').getValues();

//google doc

let copyFile = DriveApp.getFileById("template-id").makeCopy(),
        copyID = copyFile.getId(),
        copyDoc = DocumentApp.openById(copyID),
        copyBody = copyDoc.getBody(),
        copyHeader = copyDoc.getHeader()

//Replace text

const body = copyDoc.getBody()
body.replaceText("{{Tabel_angajati}}",Tabel_angajati) 

When I run this script the table in doc it's a line of values, not a tabel.

CodePudding user response:

Modification points:

  • In your script, replacement of replaceText(searchPattern, replacement) is a string type. The value retrieved by getValues() is a 2-dimensional array. In this case, when this 2-dimensional array is used to replacement, it seems that toString() is used. By this, a line of values occurs. I thought that this might be the reason for your issue.

  • In your script, the values are retrieved by getValues(). In this case, I thought that getDisplayValues() might be suitable.

When these points are reflected in a sample script, how about the following sample script?

Sample script:

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var Tabel_angajati = ss.getRangeByName('Tabel_angajati').getDisplayValues();

  var copyFile = DriveApp.getFileById("template-id").makeCopy(); // Please set your Document ID.
  var copyID = copyFile.getId();
  var copyDoc = DocumentApp.openById(copyID);

  var body = copyDoc.getBody();
  var search = "{{Tabel_angajati}}";
  var s = body.findText(search);
  while (s) {
    var e = s.getElement();
    const i = body.getChildIndex(e.getParent());
    e.removeFromParent();
    body.insertTable(i, Tabel_angajati);
    s = body.findText(search, s);
  }
}
  • When this script is run, the values from the named range of Tabel_angajati are retrieved, and a table is put to {{Tabel_angajati}} as the replacement.

References:

  • Related