'The problem with saving a file through a loop in Apps Script

I really need help. I made a script that inserts values from a table into a Google document. A new document is created for each line. But for some reason, depending on the number of lines in the table, some contracts are saved as an empty template (at the same time, with a different number of lines, different contracts are saved correctly and incorrectly). Please help me, I have already tried all the options.

my code with comments:

    function Creator() {
  // this is a template file
    const docFile = DriveApp.getFileById("1jsPQjkz4eXImbPMCQmO48LRg2gPiN6mIIx5A9nzLTOw");

 // this is the directory for new files
  const tempFolder = DriveApp.getFolderById("1wfcoEm1YbOgWV1ZNZUCM4PElc5DawzoK");

    
    var list = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
//we determine the number of rows
    var l=list.getLastRow();

  
    var a1 = list.getRange(2, 2).getValue()

//take the values of the columns from the table
    for (var i=2; i <= l; i++) {
    
    var a2 = list.getRange(i, 2).getValue();

    var a3 = list.getRange(i, 8).getValue();

    var a4 = list.getRange(i, 7).getValue();
   
    var a5 = list.getRange(i, 5).getValue();

    var a6 = list.getRange(i, 3).getValue();

    var a7 = "действующий(ая) на основании Уведомления о постановке на учет физического лица в налоговом органе"

    var a8 = list.getRange(i, 6).getValue();

// make a copy of the template

     const tempFile = docFile.makeCopy(a2, tempFolder);



// open the created copy

     const tempDocFile = DocumentApp.openById(tempFile.getId());

// copy file body

     const body = tempDocFile.getBody();
 
    
   

//replacing values in the template
   
    body.replaceText("{ФИО}", a2); 
    body.replaceText("{ДАТА}", a3);
    body.replaceText("{РЕКВИЗИТЫ}", a4);
    body.replaceText("{КОНТАКТЫ}", a6);
    if(a5 == 'ИП'){
    body.replaceText("{ОБРАЩЕНИЕ}", "Индивидуальный предприниматель");
    body.replaceText("{ОСНОВАНИЯ}", a7);  
    body.replaceText("{ОГРН}", a8);
    body.replaceText("{ПОДПИСАНТ}", a2);
    }else{
      body.replaceText("{ОБРАЩЕНИЕ}", "Зарегистрированный(ая) как плательщик налога на профессиональный доход");
          body.replaceText("{ОСНОВАНИЯ}"," ");  
    body.replaceText("{ОГРН}", "");
    }

   
   tempDocFile.saveAndClose();
   
      }
      
 
  
  

}


Solution 1:[1]

Try it this way:

function Creator() {
  const docFile = DriveApp.getFileById("1jsPQjkz4eXImbPMCQmO48LRg2gPiN6mIIx5A9nzLTOw");
  const tempFolder = DriveApp.getFolderById("1wfcoEm1YbOgWV1ZNZUCM4PElc5DawzoK");
  var list = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  let vs = list.getRange(2, 1, list.getLastRow() - 1, list.getLastColumn()).getValues();
  vs.forEach((r, i) => {
    const tempFile = docFile.makeCopy(r[1], tempFolder);
    const tempDocFile = DocumentApp.openById(tempFile.getId());
    const body = tempDocFile.getBody();
    body.replaceText("{???}", r[1]);
    body.replaceText("{????}", r[7]);
    body.replaceText("{?????????}", r[6]);
    body.replaceText("{????????}", r[2]);
    if (r[4] == '??') {
      body.replaceText("{?????????}", "?????????????? ???????????????");
      body.replaceText("{?????????}", "???????????(??) ?? ????????? ??????????? ? ?????????? ?? ???? ??????????? ???? ? ????????? ??????");
      body.replaceText("{????}", r[5]);
      body.replaceText("{?????????}", r[1]);
    } else {
      body.replaceText("{?????????}", "??????????????????(??) ??? ?????????? ?????? ?? ???????????????? ?????");
      body.replaceText("{?????????}", " ");
      body.replaceText("{????}", "");
    }
    tempDocFile.saveAndClose();
  })
}

Sources

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

Source: Stack Overflow

Solution Source
Solution 1