Scroll to Top
💻
Free Code
Users get ready-to-use code at no cost.
📋
Easy Copy
Copy and use the code instantly.
Quick Learning
Understand concepts fast and clearly.
📝
Step-by-Step
Follow simple instructions to implement.
📅 August 14, 2024 💻 Tutorial ⭐ Beginner Friendly

Autofill Google Docs in 1-Click with 100% Free Apps Script Code

Author Avatar

Ashish Dwivedi

Editorial Team • Tech Writer

About This Tutorial

​The blog post “Automate Google Sheets with AI for Free” by OutRightCRM provides a step-by-step guide to integrating ChatGPT with Google Sheets using a free Google Apps Script. By entering your ChatGPT API key, you can ask questions directly in your spreadsheet and receive AI-generated responses instantly. This setup streamlines tasks like data analysis, content creation, and report generation, enhancing productivity without leaving your sheet.
  1. Step 1: Click on the Copy button to copy the code snippet.
  2. Step 2: Paste the copied code into your project’s script editor.

Apps Scripts Blog

Read Blog

📂 javascript
⚡ script1.js
📂 html
🌐 template1.html
⚡ script1.js
🌐 template1.html
function onOpen() {
  const ui = SpreadsheetApp.getUi();
  ui.createMenu("OutrightStore")
    .addItem('Show Sidebar', 'showSidebar')
    .addToUi();

  // Automatically show sidebar when the spreadsheet is opened
  showSidebar();
}

// Function to create and display a custom sidebar
function showSidebar() {
  var html = HtmlService.createHtmlOutputFromFile('Sidebar4')
    .setTitle('Sidebar Form')
    .setWidth(300);
  SpreadsheetApp.getUi().showSidebar(html);
}

// Function to create headers dynamically from a form input
function createHeadersFromForm(headers) {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const headerArray = headers.split(",");

  // Set headers in the first row
  sheet.getRange(1, 1, 1, headerArray.length).setValues([headerArray]);

  // Apply formatting
  const headerRange = sheet.getRange(1, 1, 1, headerArray.length);
  headerRange.setFontWeight("bold");
  headerRange.setFontSize(14);
}

// Function to generate documents from sheet data using a template
function createDocumentsFromSheet(templateFileId) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Sheet1"); // Replace with your sheet name
  var dataRange = sheet.getDataRange();
  var dataValues = dataRange.getValues();

  // Placeholders from the first row
  var placeholders = dataValues[0];

  // Template document
  var templateDoc = DriveApp.getFileById(templateFileId);
  var templateName = templateDoc.getName();

  // Create folder to store generated documents
  var folder = DriveApp.createFolder("Generated Documents");

  // Loop through rows, starting from row 2
  for (var i = 1; i < dataValues.length; i++) {
    var row = dataValues[i];

    // Make a copy of the template
    var templateCopy = templateDoc.makeCopy(folder);
    var doc = DocumentApp.openById(templateCopy.getId());
    var body = doc.getBody();

    // Replace placeholders with row data
    for (var j = 0; j < placeholders.length; j++) {
      var placeholder = "{{" + placeholders[j] + "}}";
      var value = row[j];

      // Format dates
      if (value instanceof Date) {
        value = Utilities.formatDate(value, Session.getScriptTimeZone(), "dd/MM/yyyy");
      }

      body.replaceText(placeholder, value);
    }

    doc.saveAndClose();

    // Rename the copied file
    var copiedFile = DriveApp.getFileById(templateCopy.getId());
    copiedFile.setName(templateName + " - Row " + i);

    // Send PDF via email
    var email = row[2]; // Assuming Email is in column C (index 2)
    if (email) {
      var subject = "Generated Document from " + templateName;
      var mailBody = "Please find the generated document attached.";
      MailApp.sendEmail(email, subject, mailBody, {
        attachments: [copiedFile.getAs(MimeType.PDF)]
      });
    }
  }

  Logger.log("Generated documents folder URL: " + folder.getUrl());
}
<!DOCTYPE html>
<html>
<head>
  <base target="_top">
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f4f4f4;
      margin: 0;
      padding: 0;
    }

    .container {
      max-width: 500px;
      height: 500px;
      margin: 20px auto;
      padding: 20px;
      background-color: #fff;
      border-radius: 5px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }

    h2 {
      text-align: center;
      color: #333;
    }

    label {
      font-weight: bold;
    }

    select, input[type="text"], input[type="button"], input[type="email"] {
      width: 100%;
      padding: 10px;
      margin: 5px 0 15px 0;
      border: 1px solid #ccc;
      border-radius: 3px;
      box-sizing: border-box;
      font-size: 16px;
    }

    input[type="button"] {
      background-color: #4CAF50;
      color: white;
      border: none;
      cursor: pointer;
      margin-top: 10px;
    }

    input[type="button"]:hover {
      background-color: #45a049;
    }

    input[type="button"] + input[type="button"] {
      margin-left: 10px;
    }
  </style>
</head>
<body>
  <div class="container">
    <h2>Document Credentials</h2>
    <form id="documentForm">
      <label for="documentID">Template Document ID:</label><br>
      <input type="text" id="documentID" name="documentID" placeholder="Enter Document ID"><br><br>

      <label for="headers">Headers (comma-separated):</label><br>
      <input type="text" id="headers" name="headers" placeholder="Enter Headers"><br><br>

      <input type="button" value="Create Headers" onclick="createHeaders()">
      <input type="button" value="Submit" onclick="submitRequest()">
    </form>
  </div>

  <script>
    function createHeaders() {
      var headers = document.getElementById("headers").value;
      google.script.run.createHeadersFromForm(headers);
    }

    function submitRequest() {
      var templateFileId = document.getElementById("documentID").value;
      google.script.run.createDocumentsFromSheet(templateFileId);
    }
  </script>
</body>
</html>