IntegrationsIntermediate

How to Add a Gemini AI Formula to Google Sheets With Apps Script

Build a custom =GEMINI() spreadsheet function that sends a cell to the Gemini API and returns the answer in the next cell.

10 minIntermediate

A custom function turns any cell into an AI prompt. This guide creates a =GEMINI() formula with Google Apps Script so you can type a question in one cell and get the model answer in another, the same way you would use SUM or VLOOKUP. No add-on or paid tier is required beyond a Gemini API key.

  • A Google account with Google Sheets
  • A Gemini API key from Google AI Studio
  • A new or existing spreadsheet
  • About 10 minutes

Step 1: Get a Gemini API key

Open Google AI Studio, click Get API key, and create one in a project. Copy the key. You will paste it into the script in a moment, so keep the tab open.

Step 2: Open the Apps Script editor

In your sheet choose Extensions, then Apps Script. A code editor opens in a new tab with an empty Code.gs file. This script is bound to your spreadsheet.

Google Sheets - Extensions menu
Extensions
----------------------------------
Add-ons >
Apps Script
AppSheet >
Apps Script lives under the Extensions menu.

Step 3: Paste the custom function

Replace the contents of Code.gs with the function below and paste your key into API_KEY. UrlFetchApp makes the call to the Gemini endpoint and the function returns the generated text.

Code.gs
const API_KEY = "PASTE_YOUR_KEY_HERE";

function GEMINI(prompt) {
  const url =
    "https://generativelanguage.googleapis.com/v1beta/models/" +
    "gemini-2.5-flash:generateContent?key=" + API_KEY;
  const payload = { contents: [{ parts: [{ text: prompt }] }] };
  const res = UrlFetchApp.fetch(url, {
    method: "post",
    contentType: "application/json",
    payload: JSON.stringify(payload),
  });
  const data = JSON.parse(res.getContentText());
  return data.candidates[0].content.parts[0].text;
}

Step 4: Save, authorize, and use the formula

Click Save. Return to the sheet and type a formula that references a prompt cell. The first run prompts you to authorize the script to make external requests; approve it once and the formula recalculates like any other.

Google Sheets - Sheet1
A B
1 Prompt Answer
2 Rewrite this as a tweet... =GEMINI(A2)
3 Translate to Spanish: dog perro
Column A holds prompts; =GEMINI(A2) returns answers in B.
Watch the rate limits
Each cell that uses =GEMINI() fires a separate API call on recalculation. Dragging the formula down hundreds of rows can hit free-tier limits fast. Convert finished answers to plain values with Paste special once you are happy.

Result: you now have an AI function inside Sheets. Use it to classify feedback, draft replies, or clean up messy text columns without leaving the spreadsheet.

Watch related tutorials

Tags
#google-sheets#gemini#apps-script#api