Personalized Document Generator
Writing personalized letters repeatedly is tedious.
What this teaches
Generate personalized letters from a template. Welcome letters, enrollment notices and certificates.
Start without an account in the local application. Read/edit the input, predict a result, run the current source and verify output. A local document preview is not a real Google Doc; a fixture is not a live model response.
Input and expected result
Input tab: People. Entry function: generateLetters().
| Name | Program | Date |
|---|---|---|
| Alex Morgan | Web Development | 2026-12-01 |
| Jamie Chen | Data Analytics | 2026-12-02 |
Expected baseline: Two personalized Docs; Generated contains Name, URL, Status; template unchanged.
Exact Workspace setup
- Download and unzip this project. Use one separate bound script per lesson.
- Create a dedicated Drive folder. Create a native Google Sheet inside it, and import starter.csv into a tab named People. Check the exact headers above.
- Create a native Google Doc named Letter Template in the same folder, with this exact text:
Welcome {{NAME}}! Your program is {{PROGRAM}}. Start date: {{DATE}}. - Open the Sheet → Extensions → Apps Script. Paste finished Code.gs into the script editor. Save.
- Choose generateLetters in the function selector → Run. Review actual requested permissions. Reload the Sheet for the Workshop menu.
- Compare output with the baseline above. Check generated documents/drafts manually. No email should be sent.
- Perform the original challenge, investigate a failure and test duplicate/partial runs before scheduling. Do not install a trigger just because one manual run succeeded.
Understand the implementation
Validate folder and template, copy each document, replace placeholders using display values, and report per-row success or failure.
Key operations: DriveApp.getFileById(); makeCopy(); DocumentApp.openById(); replaceText()
Focused source spotlight
This is an excerpt, not a standalone script. The complete implementation follows.
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); }
}Complete Code.gs
// 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];
}
Four guided activities
Discover and run
Writing personalized letters repeatedly is tedious.
- Inspect the editable People table. The starter has 2 records.
- Write your predicted result in Prediction. Click Run application.
- Compare Output with: Two personalized Docs; Generated contains Name, URL, Status; template unchanged.
- Click Verify baseline; explain one result in Notes.
Expected: Two personalized Docs; Generated contains Name, URL, Status; template unchanged.
Understand and modify
Add a third person; expect three newly generated letters.
- Open Source and read generateLetters. Select the entry function in the walkthrough.
- Return to Application. Click Prepare original challenge to create a separate challenge starting state.
- For AI projects inspect the revised recorded fixture: this is supplied response data, not newly generated AI.
- Run application and use Verify challenge; approval/sidebar projects show extra required steps.
Expected: Add a third person; expect three newly generated letters.
Investigate and repair
Unresolved template
- Save a snapshot if you want to keep your experiment.
- Click Inject investigation. Change {{NAME}} in Letter Template to {{FIRST}}.
- Run application and inspect Output and Execution trace. Some investigations produce wrong/stale content rather than exceptions.
- Repair it: Restore {{NAME}}. Verify every generated welcome letter. Run again and explain the root cause.
Expected: Placeholder spelling is a contract, not a natural-language instruction.
Extend and automate
Add missing-field validation and skip already generated rows.
- Open Prompts. Select Extend and adapt the requirement to your goal.
- Build the feature in Source or export the complete project to Apps Script.
- Retest baseline and original challenge before considering scheduling.
- Use Resources → Automation readiness. Add a generated-ID column and process only new rows before scheduling.
Expected: The baseline still works; independent extension checks are designed and reviewed by you.
Original exercise
Add a third person; expect three newly generated letters.
Debugging and troubleshooting
Unresolved template
Change {{NAME}} in Letter Template to {{FIRST}}.
Hint 1
Check the exact input/response contract and identify the affected field.
Hint 2
Validate folder and template, copy each document, replace placeholders using display values, and report per-row success or failure.
Hint 3 and repair
Restore {{NAME}}. Verify every generated welcome letter.
Placeholder spelling is a contract, not a natural-language instruction.
Missing tab: check its exact name. Missing document: ensure unique native companion Docs share the Sheet’s dedicated folder. Authorization failure: review source and contact your administrator. Recorded response exhausted: add a new explicit fixture; no live AI is running. Invalid JSON: repair syntax before validating schema. Valid but unsupported content: compare each claim with source records.
Build prompt
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.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.
Knowledge check and answer key
- Which input tab does generateLetters read?
Answer
People
- Which function starts the original application?
Answer
generateLetters
- What is the baseline output you must verify?
Answer
Two personalized Docs; Generated contains Name, URL, Status; template unchanged.
- Does this project need runtime Gemini in the real Workspace baseline?
Answer
No; Gemini can help during development only.
- What limitation matters before scheduling?
Answer
Reruns create duplicate documents; do not schedule unchanged code.
Safe automation
Add a generated-ID column and process only new rows before scheduling.
Reruns create duplicate documents; do not schedule unchanged code.
Reflect and extend
Explain the transformation using one actual input row. Which incorrect value could still pass structural validation? What happens if the function runs twice or fails after creating one output? Write your explanation before building this extension: Add missing-field validation and skip already generated rows.
Source alignment
Physical slide 26; printed sequence 17 of 48. Reference source SHA-256 44d1fc9fe336af0cc1146a683f8de7521a6d616080218a5d4d7cab7aca49cf64.
Slide notes use Workshop Info B2. Verified repository resolves the active spreadsheet parent folder; this build follows the repository. Keep companion files in that dedicated lesson folder.
Pinned repository reference · Full source manifest
Five-minute presenter demonstration
0:00–0:45
Action: Open Input. Read People headers and first row.
Writing personalized letters repeatedly is tedious. This application is useful for Welcome letters, enrollment notices and certificates. We will run the verified reference code against fictional data.
0:45–1:30
Action: Ask for predictions. Click Run application, then Verify baseline.
Our baseline is Two personalized Docs; Generated contains Name, URL, Status; template unchanged. The browser displays local results. It has not connected to Google or a model.
1:30–3:00
Action: Open Source. Select generateLetters in the code walkthrough.
Validate folder and template, copy each document, replace placeholders using display values, and report per-row success or failure. The complete code is available to edit and download. The excerpt is not a standalone script.
3:00–4:15
Action: Click Prepare original challenge, inspect the changed inputs, and Run application. Complete extra review/sidebar steps if listed.
Add a third person; expect three newly generated letters. For AI lessons we edit a recorded response as well as source data. That response must be checked, not trusted.
4:15–5:00
Action: Click Verify challenge. Open Guide and read Automation considerations.
The important limitation is: Reruns create duplicate documents; do not schedule unchanged code. Before scheduling: Add a generated-ID column and process only new rows before scheduling. Explain the result yourself before moving on.