Google-sheets – How to embed Google Sheet into Google Document and keep the Google Sheet format

google docsgoogle sheetsgoogle-apps-script

How do I embed a Google Sheet into a google document and keep the Google Sheet format in the document?

I have got this far with the script but it's not working

function updateData() {
  var ssUrl = 'sheet url';
  var sheetName = 'sheet name';  // name of sheet to use
    var rangeName = 'A1:J45';    // range of values to include 

  var values = SpreadsheetApp.openByUrl(ssUrl)
                             .getSheetByName(sheetName)
                             .getRange(rangeName)
                             .getValues();

  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var ranges = doc.getNamedRanges('embeddedSheet-range');
  if (ranges.length == 0) {
       tableRange = ranges[0];
    table = tableRange.getRange().getRangeElements()[0].getElement();
    var ind = body.getChildIndex(table);
    tableRange.remove();
    body.removeChild(table);
    table = body.insertTable(ind, values);
  }
}

Best Answer

You seem to be missing the bottom section of this from Bookends original:

 }
  var rangeBuilder = doc.newRange();
  rangeBuilder.addElement(table);
  doc.addNamedRange('embeddedSheet-range', rangeBuilder.build());
}