AI Grammar and Clarity Enhancer in Google Sheets

Github https://github.com/lsvekis/Google-Apps-Script-Gemini-Projects/tree/main/AI%20Grammar%20and%20Clarity%20Enhancer%20in%20Google%20Sheets

🎯 Learning Objectives

By completing this exercise, learners will:

  1. Learn how to build an AI grammar and clarity correction tool using Gemini and Apps Script.
  2. Understand how to design two-way text comparisons (“Before” and “After”).
  3. Create cell-level and sidebar-based correction workflows.
  4. Implement batch grammar correction for full columns of text.
  5. Gain insight into prompt engineering for clarity, grammar, and tone control.

🧠 What You’ll Build

You’ll create an AI-powered Grammar and Clarity Enhancer directly in Google Sheets.
This app will:

  • Check for grammar issues, typos, and unclear phrasing.
  • Offer clearer, more polished alternatives.
  • Display “Before” vs “After” comparisons.
  • Include a sidebar for manual text correction and live preview.
  • Provide a custom formula =AI_GRAMMAR(A2) to use anywhere in Sheets.

🧾 Step 1: Create the Files

In Apps Script, create:

📂 gemini-sheets-grammar/

├── Code.gs

├── Sidebar.html

├── appsscript.json


💻 Step 2: Code.gs

Paste the following code:

/**

 * AI Grammar and Clarity Enhancer for Google Sheets using Gemini REST API

 * Author: Laurence “Lars” Svekis

 */

const GEMINI_API_KEY = ‘YOUR_API_KEY_HERE’;

const GEMINI_MODEL = ‘gemini-2.5-flash’;

const BASE_URL = ‘https://generativelanguage.googleapis.com/v1beta’;

const MAX_TOKENS = 512;

const TEMPERATURE = 0.4; // low creativity, high accuracy

// ===== MENU =====

function onOpen() {

  SpreadsheetApp.getUi()

    .createMenu(‘🧠 AI Tools’)

    .addItem(‘Open Grammar Sidebar’, ‘showGrammarSidebar’)

    .addItem(‘Insert Sample Data’, ‘insertSampleData’)

    .addToUi();

}

// ===== SIDEBAR =====

function showGrammarSidebar() {

  const html = HtmlService.createHtmlOutputFromFile(‘Sidebar’)

    .setTitle(‘Gemini Grammar Checker’);

  SpreadsheetApp.getUi().showSidebar(html);

}

// ===== GEMINI CALL =====

function callGeminiGrammarCheck(text) {

  const url = `${BASE_URL}/models/${GEMINI_MODEL}:generateContent?key=${GEMINI_API_KEY}`;

  const prompt = `

  You are a professional English editor.

  Correct grammar, spelling, and clarity issues in the following text.

  Keep the same tone and meaning. 

  Return only the corrected text (no explanation).

  Text:

  ${text}

  `;

  const payload = {

    contents: [{ role: “user”, parts: [{ text: prompt }] }],

    generationConfig: { temperature: TEMPERATURE, maxOutputTokens: MAX_TOKENS }

  };

  const options = {

    method: ‘post’,

    contentType: ‘application/json’,

    payload: JSON.stringify(payload),

    muteHttpExceptions: true

  };

  try {

    const res = UrlFetchApp.fetch(url, options);

    const data = JSON.parse(res.getContentText());

    const result = data?.candidates?.[0]?.content?.parts?.[0]?.text || ”;

    return result.trim() || ‘⚠️ No corrections returned.’;

  } catch (e) {

    return ‘❌ Error: ‘ + e.message;

  }

}

// ===== CUSTOM FUNCTION =====

// =AI_GRAMMAR(A2)

function AI_GRAMMAR(text) {

  return callGeminiGrammarCheck(text);

}

// ===== SHEET ACTIONS =====

function correctSelectionToRight() {

  const range = SpreadsheetApp.getActiveRange();

  const values = range.getValues();

  const output = [];

  for (let i = 0; i < values.length; i++) {

    const original = values[i][0];

    const corrected = callGeminiGrammarCheck(original);

    output.push([corrected]);

    Utilities.sleep(200);

  }

  const sheet = range.getSheet();

  const startRow = range.getRow();

  const nextCol = range.getColumn() + 1;

  sheet.getRange(startRow, nextCol, output.length, 1).setValues(output);

  SpreadsheetApp.getActive().toast(`✅ Corrected ${output.length} row(s).`);

}

// ===== SAMPLE DATA =====

function insertSampleData() {

  const data = [

    [‘Original Text’, ‘Corrected Text’],

    [‘The company are planning to expand there operations.’, ”],

    [‘She dont have enough experience for the role.’, ”],

    [‘This report were finished yesterday.’, ”],

    [‘We was excited about the upcoming project.’, ”],

    [‘Every employees must complete the training.’, ”]

  ];

  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();

  sheet.clearContents();

  sheet.getRange(1, 1, data.length, data[0].length).setValues(data);

  SpreadsheetApp.getActive().toast(‘✅ Sample data inserted.’);

}


🧩 Step 3: Sidebar.html

Create a new HTML file named Sidebar.html and add:

<!DOCTYPE html>

<html>

  <head>

    <meta charset=”utf-8″>

    <style>

      body { font-family: system-ui; padding: 16px; }

      textarea { width: 100%; height: 100px; }

      button { background: #1a73e8; color: white; border: 0; padding: 8px 12px; border-radius: 6px; cursor: pointer; }

      pre { background: #f1f3f4; padding: 8px; border-radius: 6px; white-space: pre-wrap; }

    </style>

  </head>

  <body>

    <h2>🧠 Grammar & Clarity Checker</h2>

    <p>Paste any text below to fix grammar and improve clarity.</p>

    <textarea id=”input” placeholder=”Enter text…”></textarea>

    <button onclick=”check()”>Check Grammar</button>

    <h3>Corrected Version:</h3>

    <pre id=”output”></pre>

    <script>

      function check() {

        const text = document.getElementById(‘input’).value;

        document.getElementById(‘output’).textContent = ‘⏳ Checking…’;

        google.script.run

          .withSuccessHandler(result => document.getElementById(‘output’).textContent = result)

          .callGeminiGrammarCheck(text);

      }

    </script>

  </body>

</html>


⚙️ Step 4: Manifest (appsscript.json)

{

  “timeZone”: “America/Toronto”,

  “exceptionLogging”: “STACKDRIVER”,

  “runtimeVersion”: “V8”,

  “oauthScopes”: [

    “https://www.googleapis.com/auth/spreadsheets”,

    “https://www.googleapis.com/auth/script.container.ui”,

    “https://www.googleapis.com/auth/script.external_request”

  ]

}


🧪 Step 5: Try It Out

  1. Save the project.
  2. Run → onOpen() → Authorize → Reload the Sheet.
  3. Click the 🧠 AI Tools → Insert Sample Data option.
  4. Select the “Original Text” column → run the Correct Selection → next column function manually in the editor (or add a button/menu).
  5. Or open the Grammar Sidebar and test sentences manually.

🧠 Example Results

Original TextCorrected Text
The company are planning to expand there operations.The company is planning to expand their operations.
She dont have enough experience for the role.She doesn’t have enough experience for the role.
This report were finished yesterday.This report was finished yesterday.

💡 Tips for Learners

  • You can modify the temperature to make corrections more or less creative.
  • You can instruct Gemini to also suggest clarity improvements or tone adjustments.
  • Try expanding the tool into a “Proofreader & Style Assistant” by adding options like:
    • Simplify text
    • Convert to professional tone
    • Add positive phrasing