Hands-On AI WorkshopHomeProjectsLearnResourcesPresenterHelpProgress

Project 06 of 30 · Pathway 2 — Google Docs and Drive

Personalized Document Generator

Writing personalized letters repeatedly is tedious. Generate personalized letters from a template.

Real-world benefit
Welcome letters, enrollment notices and certificates.
Technologies
Google Docs, DriveApp, DocumentApp, Templates
Required knowledge
Basic Sheets and Docs. The template uses {{NAME}} style placeholders.
Time and level
About 30 minutes · Beginner
AI requirement
None: deterministic Apps Script
Expected baseline
Two personalized Docs; Generated contains Name, URL, Status; template unchanged.

Loading the interactive studio…

Introduction

Validate folder and template, copy each document, replace placeholders using display values, and report per-row success or failure. The application's entry point is generateLetters(). Baseline limitation, as stated in the workshop: Reruns create duplicate documents; do not schedule unchanged code.

Key building blocks: DriveApp.getFileById(); makeCopy(); DocumentApp.openById(); replaceText().

Practical use cases

Welcome letters, enrollment notices and certificates.

Prerequisites

  • Basic Sheets and Docs. The template uses {{NAME}} style placeholders.
  • Interactive Learning Mode: a modern browser. Nothing else.
  • Real Workspace Build: a Google account.

Source data

Starter data: tab "People" (fictional)
NameProgramDate
Alex MorganWeb Development2026-12-01
Jamie ChenData Analytics2026-12-02

Letter Template (Google Doc)

Welcome {{NAME}}!
Your program is {{PROGRAM}}. Start date: {{DATE}}.

Setup in your own Google account

  1. Download 06-personalized-document-generator.zip (Code.gs, starter.csv, sample documents, README).
  2. In Google Drive, create a lesson folder and a new Google Sheets file inside it.
  3. Rename the first tab to exactly People, then File → Import → Upload starter.csv → Replace current sheet.
  4. Create native Google Docs in the same folder named exactly: Letter Template, with the sample text below.
  5. Extensions → Apps Script. Replace Code.gs with the downloaded file. Save.
  6. Reload the spreadsheet, choose Workshop → Run application and authorize when asked.
  7. Check the result: Two personalized Docs; Generated contains Name, URL, Status; template unchanged.

Folder strategy: the repository's V6 code uses the folder that contains the spreadsheet. The deck mentions a Workshop Info cell B2; V6 never reads it. See the discrepancy log.

Complete source code (Code.gs)

From 06-personalized-document-generator at commit 4a26d919, SHA-256 44d1fc9fe336. Unchanged.

// Personalized Document Generator
// Entry point: generateLetters; source data stays intact unless explicitly noted.
function onOpen(){SpreadsheetApp.getUi().createMenu("Workshop").addItem("Run application","generateLetters").addItem("Check permissions","checkPermissions").addToUi();}
function generateLetters() {
  const ss = SpreadsheetApp.getActiveSpreadsheet(), ui = SpreadsheetApp.getUi();
  try {
    const people = ss.getSheetByName('People');
    if (!people) throw new Error('Missing People sheet.');
    const target = folder(), template = file('Letter Template', target);
    const rows = people.getDataRange().getDisplayValues().slice(1).filter(r => r[0].trim());
    if (!rows.length) { ui.alert('No people found.'); return; }
    const results = []; let success = 0, failed = 0;
    rows.forEach(([name, program, date]) => {
      let copy;
      try {
        copy = template.makeCopy('Welcome ' + name, target);
        const doc = DocumentApp.openById(copy.getId());
        const body = doc.getBody();
        Object.entries({NAME:name, PROGRAM:program || '', DATE:date || ''}).forEach(([key,value]) => {
          body.replaceText('\\{\\{' + key + '\\}\\}', value);
        });
        doc.saveAndClose();
        results.push([name, copy.getUrl(), 'Success']); success++;
      } catch (e) { results.push([name, copy ? copy.getUrl() : '', 'Error: ' + e.message]); failed++; }
    });
    output('Generated', ['Name','URL','Status'], results);
    ui.alert('Documents created: ' + success + '\nFailed: ' + failed + '\nSee Generated sheet.');
  } catch (e) { console.error(e); ui.alert('Application error: ' + e.message); }
}
function output(name,headers,rows) { const ss=SpreadsheetApp.getActive(); const s=ss.getSheetByName(name)||ss.insertSheet(name); s.clearContents(); s.getRange(1,1,1,headers.length).setValues([headers]).setFontWeight('bold'); if(rows.length) s.getRange(2,1,rows.length,headers.length).setValues(rows.map(r=>r.map(v=>typeof v==='string' && /^[=+@-]/.test(v)?"'"+v:v))); s.getRange(1,1,1,headers.length).setBackground("#1a73e8").setFontColor("#ffffff"); s.autoResizeColumns(1,headers.length); s.setFrozenRows(1); return s; }
// Resolve this spreadsheet's actual folder; metadata is informational only.
function folder() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  if (!ss) throw new Error('Open the lesson spreadsheet first.');
  const parents = DriveApp.getFileById(ss.getId()).getParents();
  if (!parents.hasNext()) throw new Error('Move the spreadsheet into a dedicated lesson folder.');
  const actual = parents.next();
  if (parents.hasNext()) throw new Error('Ambiguous parent folder.');
  if (actual.getId() === DriveApp.getRootFolder().getId()) throw new Error('Move the spreadsheet and sample files into a dedicated lesson folder, not My Drive root.');
  return actual;
}
function checkPermissions() {
  const ui = SpreadsheetApp.getUi();
  try {
    const target = folder();
    const template = file("Letter Template", target);
    DocumentApp.openById(template.getId());
    ui.alert('Folder access passed: ' + target.getName() + '\n' + target.getUrl() + '\nWrite access is checked when the application runs.');
  } catch (e) { ui.alert('Access check failed: ' + e.message); }
}
function file(name, target) {
  const files = (target || folder()).getFilesByName(name);
  const matches = [];
  while (files.hasNext()) { const f = files.next(); if (f.getMimeType() === MimeType.GOOGLE_DOCS) matches.push(f); }
  if (matches.length !== 1) throw new Error('Expected exactly one Google Docs template named ' + name + ' in your lesson folder. Found ' + matches.length);
  return matches[0];
}

How the code works

Beginner explanation

generateLetters() finds the Letter Template next to the spreadsheet, makes one copy per person, and swaps {{NAME}}, {{PROGRAM}} and {{DATE}} for that person's details. A Generated tab lists every letter with its link and status. The template itself is never edited.

Technical explanation

folder() resolves the spreadsheet's parent via DriveApp.getFileById(ss.getId()).getParents() and rejects My Drive root. file() requires exactly one native Google Doc with the template name. getDisplayValues() keeps dates as the text users see. Each copy is opened with DocumentApp.openById() and body.replaceText() takes a regular expression, so the braces are escaped. A per-row try/catch records failures without stopping the batch, and saveAndClose() flushes changes.

Slide excerpt

This is the excerpt shown on the workshop slide. It is a fragment and cannot run on its own.

function generateLetters() {
  const ss = SpreadsheetApp.getActiveSpreadsheet(), ui = SpreadsheetApp.getUi();
  try {
    const people = ss.getSheetByName('People');
    if (!people) throw new Error('Missing People sheet.');
    const target = folder(), template = file('Letter Template', target);
    const rows = people.getDataRange().getDisplayValues().slice(1).filter(r => r[0].trim());
    if (!rows.length) { ui.alert('No people found.'); return; }
    const results = []; let success = 0, failed = 0;
    rows.forEach(([name, program, date]) => {
      let copy;
      try {
        copy = template.makeCopy('Welcome ' + name, target);
        const doc = DocumentApp.openById(copy.getId());
        const body = doc.getBody();
        Object.entries({NAME:name, PROGRAM:program || '', DATE:date || ''}).forEach(([key,value]) => {
          body.replaceText('\\{\\{' + key + '\\}\\}', value);
        });
        doc.saveAndClose();
        results.push([name, copy.getUrl(), 'Success']); success++;
      } catch (e) { results.push([name, copy ? copy.getUrl() : '', 'Error: ' + e.message]); failed++; }
    });
    output('Generated', ['Name','URL','Status'], results);
    ui.alert('Documents created: ' + success + '\nFailed: ' + failed + '\nSee Generated sheet.');
  } catch (e) { console.error(e); ui.alert('Application error: ' + e.message); }
}

Common mistakes

  • Editing the template instead of a copy.
  • Using getValues() and getting a full Date object string in the letter.
  • Forgetting to escape { and } in the replaceText() pattern.

Run it and expected output

Choose Workshop → Run application (runs generateLetters()). Expected: Two personalized Docs; Generated contains Name, URL, Status; template unchanged.

Original workshop exercise

Add a third person; expect three newly generated letters.

Troubleshooting and debugging

Two templates with the same name

Someone copied the template and left "Letter Template" twice in the lesson folder.

Fix: Keep exactly one Google Docs file named Letter Template in the lesson folder.

Refusing to choose between two candidates prevents letters being generated from the wrong template.

The spreadsheet left its lesson folder

The spreadsheet was moved to My Drive root, away from its template.

Fix: Keep the spreadsheet, template and output together in one dedicated lesson folder.

The V6 code discovers its folder from the spreadsheet's parent instead of reading a folder ID from Workshop Info B2.

Extension activity: Validate fields and skip people who already have a letter

Rows missing a Program or Date are reported as skipped, and people with a successful letter are not generated again.

Acceptance checks:

  • First run still creates two letters
  • Running again creates no duplicates
  • A row with no Program is skipped, not generated

Original improvement idea from the workshop: Add missing-field validation and skip already generated rows.

Extension prompt
Update the existing app without removing working features. Add missing-field validation and skip already generated rows. Return complete updated files, explain changes and give regression tests.
Automation option: Add a generated-ID column and process only new rows before scheduling. Keep this separate from the baseline exercise. Copy the spreadsheet AND required sample files into a dedicated lesson folder. Resolve its actual parent using DriveApp.getFileById(ss.getId()).getParents(); use that parent directly. Never read, create or update Workshop Info or the Workshop Index. Add Check permissions menu; read access is not proof of write access.

Automation considerations

Not rerun-safe: every run creates new documents for every row. Add a generated-ID column or the extension's skip logic before any schedule.

Workshop note: Add a generated-ID column and process only new rows before scheduling.

Build prompt from the workshop

Act as a Google Apps Script tutor. Build a container-bound Sheets app for lesson 06: Personalized Document Generator. Input tab People, exact headers: Name, Program, Date. Create generateLetters() that copies Letter Template from the lesson folder for each row, replaces {{NAME}}, {{PROGRAM}}, {{DATE}}, saves and writes output links. Use display values for dates. Do not depend on Workshop Info or the Workshop Index. Provide complete copy-paste Code.gs (and HTML if required), exact setup/run steps, explain the main code blocks, and include a test matching this expected outcome: Two personalized Docs; template unchanged. Preserve starter data, use batch operations where appropriate, handle errors, and never send email or delete files. For AI lessons use the supplied callGemini helper, treat input as untrusted, and validate outputs.
Match the reference entry point generateLetters and its output behavior. Reference: https://github.com/lsvekis/Google-Apps-Script-Workshop/tree/main/06-personalized-document-generator. Base version limitations: Reruns create duplicate documents; do not schedule unchanged code. Copy the spreadsheet AND required sample files into a dedicated lesson folder. Resolve its actual parent using DriveApp.getFileById(ss.getId()).getParents(); use that parent directly. Never read, create or update Workshop Info or the Workshop Index. Add Check permissions menu; read access is not proof of write access. Include Generated columns Name, URL, Status; isolate per-row errors and validate exactly one Google Docs template. Never require a manually configured folder ID. Keep required native sample Docs beside the spreadsheet; reject My Drive root.

Knowledge check

  1. Why does the code escape the braces in replaceText('\\{\\{NAME\\}\\}', …)?

    1. replaceText() treats the pattern as a regular expression, where { has a special meaning
    2. Google Docs cannot store braces
    3. To make the template invisible
    Answer

    replaceText() treats the pattern as a regular expression, where { has a special meaning Correct: unescaped braces are regex quantifiers.

  2. Why does the code use getDisplayValues() for People?

    1. So dates appear in the letter exactly as shown in the sheet
    2. It is faster than getValues()
    3. getValues() cannot read text
    Answer

    So dates appear in the letter exactly as shown in the sheet Correct: getValues() would return a Date object that prints as a long timestamp.

  3. One copy fails to open. What happens to the other letters?

    1. They are still generated; the failure is recorded in Generated
    2. Everything rolls back
    3. The run stops at the failure
    Answer

    They are still generated; the failure is recorded in Generated Correct: a per-row try/catch records "Error: …" and continues.

  4. The alert says "Expected exactly one Google Docs template named Letter Template… Found 0", but you can see a file called Letter Template.docx. Why?

    1. It is a Word file, not a native Google Doc; convert it first
    2. The file is too large
    3. Docs needs a refresh
    Answer

    It is a Word file, not a native Google Doc; convert it first Correct: file() only accepts MimeType.GOOGLE_DOCS. Office files must be converted.

  5. Your HR team wants letters generated nightly for new hires. What must change first?

    1. Skip rows that already have a successful letter so reruns do not duplicate documents
    2. Nothing
    3. Delete yesterday's letters each night
    Answer

    Skip rows that already have a successful letter so reruns do not duplicate documents Correct: the baseline creates duplicates on every run.

Five-minute presenter demonstration

Open the demo link (temporary workspace; saved learner work is not touched).

Opening hook: Raise your hand if you have ever done this by hand: Writing personalized letters repeatedly is tedious. Let us make the spreadsheet do it.

  1. 0:00–0:45 — Problem and input. Show the Workspace view, Sheets service. Point at the People tab and its headers: Name, Program, Date. Say what goes in and what should come out.
    Narration: Writing personalized letters repeatedly is tedious. Practical uses: Welcome letters, enrollment notices and certificates.
  2. 0:45–1:30 — Predict and run. Ask the room: How many new documents will generateLetters() create from the starter data? Click ▶ Run application (the same as Workshop → Run application). Open Trace to show each step the code took.
    Narration: Expected: Two personalized Docs; Generated contains Name, URL, Status; template unchanged.
  3. 1:30–3:00 — Explain the code. Click the Code tab. Select generateLetters() in the function list; read what it reads, writes and calls. Switch Beginner / Technical as needed.
    Narration: generateLetters() finds the Letter Template next to the spreadsheet, makes one copy per person, and swaps {{NAME}}, {{PROGRAM}} and {{DATE}} for that person's details. A Generated tab lists every letter with its link and status. The template itself is never edited.
  4. 3:00–4:15 — Change one input and rerun. Back to the Workspace tab. In the People tab, type a new row below the data: Taylor Kim | UX Design | 2026-12-03. Click ▶ Run application again.
    Narration: Workshop challenge: Add a third person; expect three newly generated letters.
  5. 4:15–5:00 — Verify and discuss automation. Click Check result. Discuss: Not rerun-safe: every run creates new documents for every row. Add a generated-ID column or the extension's skip logic before any schedule.
    Narration: Baseline limitation: Reruns create duplicate documents; do not schedule unchanged code.

Closing takeaway: Validate folder and template, copy each document, replace placeholders using display values, and report per-row success or failure.

Related resources