'Creating a Google Doc from a template with tables in Google Apps Script

This is a Google Apps Script to create a Google Doc from a template and the values in a Google Spreadsheet.

It takes the fields from the active row in your Google Spreadsheet (the one with a highlighted cell or row) and using a Google Doc template (identified by TEMPLATE_ID) creates a doc with these fields replacing the placeholders in the template.
The place-holders are identified by having % around them, e.g. %Name%. It is run using the custom “Create Document” menu that is created in the sheet.

Now, my question is, if I have also a table, with the normal placeholders, (see the image or the link) how could I proceed if I put also the placeholder %Table 1% in the doc template?

enter image description here

In this case, the placeholders %Name%, %Surname%, %Fruit% have to take the values only from the second row. The placeholder %Table 1% have to take the values until the end of the table (row 5).

https://docs.google.com/spreadsheets/d/1l3bCuyRnz_ylMHMfhbRC-_L5bLkWwEkrzGKgy46Kvnk/edit?usp=sharing

function myfunction() {
      var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
    var TEMPLATE_ID = 'xxx';
    //var TEMPLATE_ID = ss.getRange("TEMPLATEID").getValue();
     var ui = SpreadsheetApp.getUi();
      if (TEMPLATE_ID === '') {
        
        SpreadsheetApp.getUi().alert('TEMPLATE_ID needs to be defined in code.gs')
        return
      }
      
      var copyFile = DriveApp.getFileById(TEMPLATE_ID).makeCopy(),
          copyId = copyFile.getId(),
          copyDoc = DocumentApp.openById(copyId)
           var docFile = DriveApp.getFileById(copyFile.getId()); // Get Document as File
      
          var FILE_NAME = ui.prompt('Insert file name:', ui.ButtonSet.OK);
          FILE_NAME.getSelectedButton() == ui.ButtonSet.OK
          copyDoc.setName(FILE_NAME.getResponseText())
          
      var copyBody = copyDoc.getActiveSection(),
          activeSheet = SpreadsheetApp.getActiveSheet(),
          numberOfColumns = activeSheet.getLastColumn(),
          activeRowIndex = activeSheet.getActiveRange().getRowIndex(),
          activeRow = activeSheet.getRange(activeRowIndex, 1, 1, numberOfColumns).getValues(),
          headerRow = activeSheet.getRange(1, 1, 1, numberOfColumns).getValues(),
          columnIndex = 0
        
      for (;columnIndex < headerRow[0].length; columnIndex++) {
          var nextValue = formatString(activeRow[0][columnIndex])
          copyBody.replaceText('%' + headerRow[0][columnIndex] + '%', nextValue)                         
        }
      
      copyDoc.saveAndClose()
      
      SpreadsheetApp.getUi().alert('File doc created!!')
      
    }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source