# Google Sheets for AI Agents — Read, Append, Replace (`brito17/google-sheets-for-ai-agents`) Actor

Send any Apify scraper’s results straight into Google Sheets, or let AI agents read and write your sheets. Read, append, replace or clear. Just share your sheet with one email address: no OAuth, no Google Cloud setup. Reliable for scheduled runs.

- **URL**: https://apify.com/brito17/google-sheets-for-ai-agents.md
- **Developed by:** [Brady](https://apify.com/brito17) (community)
- **Security:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.50 / 1,000 row writtens

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Google Sheets for AI Agents — Read, Append, Replace

Read, append, replace or clear any Google Sheet in one step. **No OAuth popups, no Google Cloud setup.** Paste the sheet link, share the sheet with one email address, and run.

Built to be reliable for **AI agents (Claude, ChatGPT, Cursor via the Apify MCP server)**, Apify integrations, Make/Zapier/n8n and scheduled runs.

### Setup in 30 seconds

1. Open your Google Sheet → click **Share**.
2. Add **`sheets-bot@sheets-bot-512104.iam.gserviceaccount.com`** as an **Editor** (Viewer is enough if you only read).
3. Paste the sheet URL into this Actor and pick an action.

That's it. If you forget step 2, the run tells you exactly what to do.

### What it does

| Action | What happens |
|---|---|
| `read` | Returns every row as JSON. Row 1 is used as field names. |
| `append` | Adds rows to the bottom (from `rows` or from another Actor's dataset). Object keys are matched to your existing columns (case-insensitive). New keys become new columns automatically. |
| `replace` | Clears the tab (or a range) and writes your rows. Validates your data **before** clearing, so a bad input never wipes your sheet. |
| `clear` | Empties the tab or a range. |
| `listTabs` | Lists the tabs in the spreadsheet. |

### Why this one

- **Appends never overwrite.** Append always adds below your existing data.
- **Plain-English errors.** "Share the sheet with … as an Editor", "Tab 'Leads2' not found. Available tabs: 'Leads', 'Archive'" — so an AI agent can fix the problem itself.
- **Accepts whatever you have.** Full URL or just the ID, tab by name or from the `#gid=` in the link, rows as objects, arrays, or a JSON string.
- **Safe by default.** Values are stored exactly as sent (`RAW`), so scraped text like `=IMPORTXML(...)` can never execute as a formula. Switch to `USER_ENTERED` if you want Sheets to parse formulas and dates.
- **Big writes just work.** Large batches are split automatically, and Google rate limits are retried with backoff.
- **Creates missing tabs** on append/replace.

### Examples

**Append leads from another Actor or an AI agent**

```json
{
  "spreadsheet": "https://docs.google.com/spreadsheets/d/1AbC.../edit",
  "action": "append",
  "sheetName": "Leads",
  "rows": [
    { "name": "Ann Lee", "email": "ann@example.com", "company": "Acme" },
    { "name": "Bo Chan", "email": "bo@example.com", "city": "Ottawa" }
  ]
}
```

If `Leads` has columns `name | email | company`, a `city` column is added for Bo.

**Read a tab as JSON**

```json
{ "spreadsheet": "1AbC...", "action": "read", "sheetName": "Leads", "maxRows": 500 }
```

Output (dataset):

```json
[{ "name": "Ann Lee", "email": "ann@example.com", "company": "Acme", "city": "" }]
```

**Overwrite a report tab every day (schedule this run)**

```json
{ "spreadsheet": "1AbC...", "action": "replace", "sheetName": "Daily report", "rows": [ ... ] }
```

### Use it from an AI agent (MCP)

Connect your agent to `https://mcp.apify.com` and add this Actor as a tool. The inputs are simple enough for an agent to fill in: `spreadsheet`, `action`, `sheetName`, `rows`.

### Send any scraper's results to Sheets automatically

Run this Actor every time another Actor finishes, so its results land in your sheet with no clicking:

1. Open your scraper (Google Maps, Instagram, anything) → **Integrations** tab → **Add integration** → pick this Actor.
2. Use this input:

```json
{
  "spreadsheet": "https://docs.google.com/spreadsheets/d/1AbC.../edit",
  "action": "append",
  "sheetName": "Leads",
  "datasetId": "{{resource.defaultDatasetId}}"
}
```

3. Schedule the scraper. Each run appends its new results to the sheet.

Good to know:

- **Nested fields get their own columns** (`address.city`, `address.zip`) instead of a blob of JSON. Turn off **Flatten nested fields** to keep them as JSON.
- **Pick columns** with `datasetFields`, e.g. `["title", "phone", "address.city"]`. They're written in that order.
- **Want a fresh copy each time?** Use `"action": "replace"`. If the scraper run returns nothing, your sheet is left untouched instead of wiped.

You can also copy any existing dataset by pasting its ID into **Dataset ID**.

### Output

- `read` and `listTabs`: the rows/tabs are in the **dataset**.
- Every run saves a summary to the `OUTPUT` record, e.g.
  `{ "ok": true, "action": "append", "sheetName": "Leads", "rowsWritten": 2, "headers": ["name","email","company","city"] }`
- Write actions also push that summary to the dataset, so agents see the result directly.

### Pricing

Pay per event: you're charged per row read or written. Listing tabs and clearing are not charged beyond the small run start fee. Set a **max cost per run** and the Actor stops at your limit instead of overspending.

### Privacy and security

- The Actor only touches sheets you explicitly share with it, and only for the run you start.
- Sheet contents aren't stored anywhere except your own run's dataset.
- Prefer not to share with a shared bot? Paste your own Google Cloud service account key in **Advanced → Your own service account key** (stored encrypted) and share the sheet with that account instead.

### Limits (Google's, not ours)

- 10 million cells per spreadsheet.
- Very large reads may be slow; use `range` or `maxRows` to fetch only what you need.

### Questions or bugs

Open an issue on the **Issues** tab. Fast replies.

# Actor input Schema

## `spreadsheet` (type: `string`):

Paste the full Google Sheets link (https://docs.google.com/spreadsheets/d/.../edit) or just the ID. IMPORTANT: share the sheet (Share button → add as Editor) with sheets-bot@sheets-bot-512104.iam.gserviceaccount.com.

## `action` (type: `string`):

read = get rows as JSON. append = add rows to the bottom. replace = clear the tab (or range) and write new rows. clear = empty the tab (or range). listTabs = list the tabs in the spreadsheet.

## `sheetName` (type: `string`):

Which tab to use. Leave empty to use the tab from the URL (gid=...) or the first tab. For append/replace, a missing tab is created automatically.

## `rows` (type: `array`):

For append/replace. Either objects (keys become column headers, matched case-insensitively to existing headers): \[{"name":"Ann","email":"ann@x.com"}] — or plain arrays: \[\["Ann","ann@x.com"]]. Not needed if you use Dataset ID.

## `datasetId` (type: `string`):

Copy results from an Apify dataset into the sheet, e.g. a scraper run. In an Actor integration (run this after another Actor finishes), use {{resource.defaultDatasetId}}. Works with append and replace. If the dataset is empty, the sheet is left untouched.

## `datasetFields` (type: `array`):

Only these fields, in this order, become columns. Nested fields use dots, e.g. location.lat. Leave empty for all fields.

## `datasetLimit` (type: `integer`):

Stop after this many dataset items. Leave empty for all.

## `flattenNested` (type: `boolean`):

Split nested objects into their own columns (address.city, address.zip) instead of putting JSON text in one cell.

## `range` (type: `string`):

A1 range to limit read/clear/replace, e.g. A1:D500, A:C or 2:100. Leave empty for the whole tab.

## `firstRowIsHeader` (type: `boolean`):

When reading, use row 1 as field names and return each row as an object. Turn off to get raw arrays.

## `maxRows` (type: `integer`):

Stop after this many rows when reading. Leave empty for all.

## `addMissingColumns` (type: `boolean`):

When appending objects with fields the sheet doesn't have yet, add them as new header columns. If off, those fields are skipped (and listed in the log).

## `writeHeaders` (type: `boolean`):

When replacing with objects, write their keys as the first row.

## `valueInputOption` (type: `string`):

RAW (default, safest) stores text exactly as sent, so scraped text like "=IMPORTXML(...)" can never run as a formula. USER_ENTERED makes Sheets parse values like typing them in: formulas, dates and currency.

## `rawValues` (type: `boolean`):

Return numbers as numbers (1234.5) instead of as displayed ("$1,234.50").

## `readFormulas` (type: `boolean`):

When reading, return the formulas themselves (e.g. =SUM(A1:A5)) instead of their results.

## `createSheetIfMissing` (type: `boolean`):

If the tab name doesn't exist, create it automatically when appending or replacing.

## `serviceAccountKey` (type: `string`):

Only if you don't want to share your sheet with our bot: paste your own Google Cloud service account JSON key. Stored encrypted.

## Actor input object example

```json
{
  "spreadsheet": "https://docs.google.com/spreadsheets/d/YOUR_SHEET_ID/edit",
  "action": "read",
  "rows": [
    {
      "name": "Ann",
      "email": "ann@example.com"
    }
  ],
  "flattenNested": true,
  "firstRowIsHeader": true,
  "addMissingColumns": true,
  "writeHeaders": true,
  "valueInputOption": "RAW",
  "rawValues": false,
  "readFormulas": false,
  "createSheetIfMissing": true
}
```

# Actor output Schema

## `results` (type: `string`):

For read: one item per sheet row (keys = header row). For listTabs: one item per tab. For append/replace/clear: a summary with ok, rowsWritten and headers.

## `summary` (type: `string`):

JSON summary of the run: ok, action, spreadsheetId, sheetName, rowsRead/rowsWritten, and error if it failed.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "spreadsheet": "https://docs.google.com/spreadsheets/d/YOUR_SHEET_ID/edit",
    "rows": [
        {
            "name": "Ann",
            "email": "ann@example.com"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("brito17/google-sheets-for-ai-agents").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "spreadsheet": "https://docs.google.com/spreadsheets/d/YOUR_SHEET_ID/edit",
    "rows": [{
            "name": "Ann",
            "email": "ann@example.com",
        }],
}

# Run the Actor and wait for it to finish
run = client.actor("brito17/google-sheets-for-ai-agents").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "spreadsheet": "https://docs.google.com/spreadsheets/d/YOUR_SHEET_ID/edit",
  "rows": [
    {
      "name": "Ann",
      "email": "ann@example.com"
    }
  ]
}' |
apify call brito17/google-sheets-for-ai-agents --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,brito17/google-sheets-for-ai-agents"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/Nl9xAfXjY9dlmMdvq/builds/4QRZOqiBOzywyaScP/openapi.json
