Automatically Populate Google Docs from a Spreadsheet

When running this custom script, docs are created and linked, yet data placeholders remain unchanged. Why is the spreadsheet data not replacing the template values?

function initCustomMenu() {
  const ui = SpreadsheetApp.getUi();
  ui.createMenu('DocsMaker')
    .addItem('Generate Document', 'assembleDocument')
    .addToUi();
}

function assembleDocument() {
  const baseTemplate = DriveApp.getFileById('TEMPLATE_ID');
  const folderTarget = DriveApp.getFolderById('FOLDER_ID');
  const dataSheet = SpreadsheetApp.getActive().getSheetByName('Responses');
  const dataRows = dataSheet.getDataRange().getValues();
  dataRows.slice(1).forEach((record, idx) => {
    if (record[6]) return;
    let docCopy = baseTemplate.makeCopy(`${record[0]} Record`, folderTarget);
    let currentDoc = DocumentApp.openById(docCopy.getId());
    let docBody = currentDoc.getBody();
    docBody.replaceText('<<Name>>', record[0]);
    currentDoc.saveAndClose();
    dataSheet.getRange(idx + 2, 7).setValue(currentDoc.getUrl());
  });
}

The issue might not be with the document creation itself but with how the placeholders in the template are defined. In my experience, if there’s any inconsistency in the placeholder formatting, for instance extra spaces or different punctuation, the replaceText method will not identify and update them. It is important to double-check the exact text in the document. In a similar case, I had to ensure that the placeholder strings were exactly identical to those in the template. Another area to look into is whether the document is fully saved when the script attempts further operations on it.