π Apps Script + Gemini Mastery β Issue #16
AI Spreadsheet Data Analyzer
Use Apps Script + Gemini to automatically analyze spreadsheet data, identify trends, detect anomalies, and generate plain-English insights.
β What You Will Build
In this issue, youβll build an AI Data Analyzer for Google Sheets that can:
π Read spreadsheet data
π§ Analyze it with Gemini
π Identify trends and patterns
β οΈ Detect anomalies or unusual values
π Generate a written summary of key insights
π Output the results into a new sheet or sidebar
π§ Why This Project Matters
Many people can collect data.
Far fewer can quickly interpret it.
This tool helps bridge that gap.
Instead of staring at rows and columns, users can ask for:
- key trends
- performance summaries
- anomalies
- recommendations
It transforms raw data into decision-ready insights.
π§© Architecture
Spreadsheet data
β
Apps Script reads values
β
Gemini analyzes patterns
β
Apps Script writes insights back to Sheets
π§± Step 1 β Add the Menu
Code.gs
function onOpen() {
SpreadsheetApp.getUi()
.createMenu("AI Tools")
.addItem("AI Data Analyzer", "showAnalyzerSidebar")
.addToUi();
}function showAnalyzerSidebar() {
SpreadsheetApp.getUi().showSidebar(
HtmlService.createHtmlOutputFromFile("Sidebar")
.setTitle("AI Data Analyzer")
);
}
π§± Step 2 β Sidebar UI
Sidebar.html
<div style="font-family:Arial;padding:14px;"> <h2>AI Data Analyzer</h2> <label><b>What would you like analyzed?</b></label> <textarea id="prompt" style="width:100%;height:90px;">
Example: Analyze sales trends and identify anomalies
</textarea> <button onclick="analyze()">Analyze Data</button> <pre id="output" style="white-space:pre-wrap;margin-top:12px;"></pre><script>function analyze() { document.getElementById("output").textContent = "Analyzing data..." google.script.run
.withSuccessHandler(res => {
document.getElementById("output").textContent = res
})
.analyzeSheetData(
document.getElementById("prompt").value
)}</script></div>
π§± Step 3 β Read Spreadsheet Data
SheetReader.gs
function getSheetData_() {
const sheet = SpreadsheetApp.getActiveSheet();
const values = sheet.getDataRange().getValues(); return {
sheetName: sheet.getName(),
headers: values[0],
rows: values.slice(1)
};
}
π§± Step 4 β Send Data to Gemini
DataAnalyzer.gs
function analyzeSheetData(userPrompt) {
if (!userPrompt) return "Enter an analysis request."; const data = getSheetData_(); const prompt = `
You are an expert spreadsheet data analyst.Analyze the spreadsheet data below.Sheet name:
${data.sheetName}Headers:
${data.headers.join(", ")}Rows:
${JSON.stringify(data.rows.slice(0, 200))}User request:
${userPrompt}Return JSON in this format:{
"summary": "short overall summary",
"insights": [
"insight 1",
"insight 2"
],
"anomalies": [
"anomaly 1",
"anomaly 2"
],
"recommendations": [
"recommendation 1",
"recommendation 2"
]
}
`; let result; try {
result = callGemini(prompt, "");
} catch (e) {
return "Gemini error: " + e;
} result = result.replace(/```json/g, "").replace(/```/g, "").trim(); let json;
try {
json = JSON.parse(result);
} catch (e) {
Logger.log(result);
return "Could not parse Gemini output.";
} return writeAnalysisToSheet_(json);
}
π§± Step 5 β Write Insights to a New Sheet
AnalysisWriter.gs
function writeAnalysisToSheet_(analysis) {
const ss = SpreadsheetApp.getActiveSpreadsheet(); let sheet = ss.getSheetByName("AI Analysis"); if (!sheet) {
sheet = ss.insertSheet("AI Analysis");
} else {
sheet.clear();
} let row = 1; sheet.getRange(row++, 1).setValue("Summary");
sheet.getRange(row++, 1).setValue(analysis.summary || ""); row++;
sheet.getRange(row++, 1).setValue("Insights");
(analysis.insights || []).forEach(item => {
sheet.getRange(row++, 1).setValue(item);
}); row++;
sheet.getRange(row++, 1).setValue("Anomalies");
(analysis.anomalies || []).forEach(item => {
sheet.getRange(row++, 1).setValue(item);
}); row++;
sheet.getRange(row++, 1).setValue("Recommendations");
(analysis.recommendations || []).forEach(item => {
sheet.getRange(row++, 1).setValue(item);
}); return "Analysis written to AI Analysis sheet.";
}
π§± Step 6 β Gemini Helper
Reuse the same helper from earlier issues.
GeminiHelpers.gs
const GEMINI_API_KEY = "YOUR_API_KEY_HERE";
const GEMINI_MODEL = "gemini-2.5-flash";function callGemini(prompt, text) {
const url = `https://generativelanguage.googleapis.com/v1/models/${GEMINI_MODEL}:generateContent?key=${GEMINI_API_KEY}`; const payload = {
contents: [{
parts: [{
text: prompt + (text ? "\n\n" + text : "")
}]
}]
}; const res = UrlFetchApp.fetch(url, {
method: "post",
contentType: "application/json",
payload: JSON.stringify(payload)
}); const json = JSON.parse(res.getContentText());
return json.candidates[0].content.parts[0].text;
}
π§ͺ Example Requests
Users can ask:
Analyze sales trends and identify anomalies
Summarize customer performance by region
Find unusual values and suggest next steps
Explain this spreadsheet in plain English
π₯ Advanced Exercises
Readers can extend this by adding:
β
automatic chart generation from insights
β
KPI extraction
β
multi-sheet analysis
β
anomaly scoring
β
export to Google Docs report
π Next Issue (#17)
AI Spreadsheet Cleaner + Fixer
Describe data cleanup rules β Apps Script cleans and standardizes the spreadsheet automatically.