# Google Sheets Export — append, replace, upsert (no OAuth) (`teal_blacksmith/google-sheets-export`) Actor

Writes Apify dataset rows or your own JSON rows into a Google Sheet by appending, replacing or upserting. Uses a Google service account instead of OAuth, so it works from integrations, schedules and AI agents. Clear error messages, cell-limit check before writing.

- **URL**: https://apify.com/teal_blacksmith/google-sheets-export.md
- **Developed by:** [도영 김](https://apify.com/teal_blacksmith) (community)
- **Categories:** Integrations, Automation, Developer tools
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $5.00 / 1,000 export runs

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

### What does Google Sheets Export do?

It writes rows into a Google Sheet: from any Apify dataset, from an integration attached to another Actor, or from JSON you pass in. You choose how: **append**, **replace** or **upsert**.

It was built around the things that usually go wrong when you export to Sheets:

- **No OAuth and no setup.** It signs in with a Google *service account*: share your sheet with one email address and run. There is no browser consent screen to complete. It runs unattended from schedules, integrations, the API and AI agents (MCP).
- **Any valid spreadsheet ID is accepted.** Paste the full URL or the bare ID. IDs are not required to be a fixed length.
- **Append really appends.** Existing rows are never touched. New rows go after the last non-empty row.
- **Errors say what to do.** "Share the spreadsheet with `name@project.iam.gserviceaccount.com` as Editor", "spreadsheet ID is wrong or not shared", "enable the Sheets API in project X" — not a stack trace.
- **Limits are checked before writing.** If the result would exceed Google's cell limit, nothing is written and the message gives the current cells, the cells to add and the limit.
- **Failures are retried.** Rate limits (429) and server errors (5xx) are retried with exponential backoff and jitter, honouring `Retry-After`.

### Quick start — one step, no Google Cloud setup

**Share your spreadsheet with this address as Editor:**

```
sheets-export@sheets-export-actor.iam.gserviceaccount.com
```

Open the sheet, click **Share**, paste the address, choose **Editor**, click **Send**. Then paste the spreadsheet URL into the Actor and run it. Leave the *Service account key* field empty.

If the sheet is not shared, the run fails with: `Google denied access. Share the spreadsheet with <email> as Editor ...` — and nothing else happens.

This shared service account can open **only** spreadsheets that someone has explicitly shared with it. It is used by everyone who runs this Actor without their own key, and its Google API quota (300 requests per minute) is shared too.

### Prefer your own service account? (about 5 minutes, once)

Use your own if you want your own quota, or do not want to share a sheet with an account you do not control.

1. In [Google Cloud Console](https://console.cloud.google.com/) create or pick a project, then open **APIs & Services > Library**, search **Google Sheets API** and click **Enable**.
2. Open **IAM & Admin > Service accounts > Create service account**. Give it any name. No roles are needed.
3. Open the new service account, go to **Keys > Add key > Create new key > JSON**. A `.json` file downloads.
4. Share your spreadsheet with that service account's email address (it ends in `.iam.gserviceaccount.com`) as **Editor**.
5. Paste the **whole contents of the JSON file** into the Actor's *Service account key* field. Your own key always takes priority over the shared account.

### Modes

Header row is row 1. Existing columns are never reordered or renamed. Columns in your data that the sheet lacks are added at the right end. Sheet columns missing from your data stay blank for new rows.

**append** (default). Sheet has `name | age`, you send `{name: "Cy", age: 5}`:

| Before | After |
|---|---|
| Ann, 30 | Ann, 30 |
| Bob, 40 | Bob, 40 |
| | **Cy, 5** |

**replace.** Clears the tab, then writes header and rows. If the source is empty, the sheet is left untouched.

| Before | After (sent `{n: "only"}`) |
|---|---|
| name, age / Ann, 30 / Bob, 40 | n / only |

**upsert** with `keyFields: ["id"]`. A row whose key matches an existing row overwrites that row in place (only the columns you send; other sheet columns keep their values). Others are appended. Keys are compared as trimmed text.

| Before | Sent | After |
|---|---|---|
| 1, Ann / 2, Bob | `{id: 2, name: "Bobby"}`, `{id: 3, name: "Cy"}` | 1, Ann / 2, **Bobby** / **3, Cy** |

### Input

| Field | Notes |
|---|---|
| `spreadsheet` | Full URL or ID. A `gid=` in the URL selects that tab. |
| `sheetName` | Tab title. Created if missing. Default: the `gid` tab, else the first tab. |
| `mode` | `append` (default), `replace`, `upsert`. |
| `keyFields` | Required for upsert. |
| `datasetId` / `rows` | Source. First present wins: `datasetId`, then integration payload, then `rows`. |
| `fields` | Column selection and order. Default: all keys, first-seen order. |
| `flatten` | Default on. Nested objects become `a.b.c` columns; lists of text/numbers are joined with `, `; lists of objects become JSON text. |
| `dedupeFields` | Drop repeats of earlier source rows; in append mode also skip rows already in the sheet. |
| `valueInputOption` | `RAW` (default) or `USER_ENTERED`. |
| `maxRows` | Stop after this many source rows. |
| `serviceAccountKey` | Secret. Full JSON key. |

**RAW vs USER_ENTERED.** With `RAW` (default) every value is stored exactly as given. Text that starts with `=`, `+`, `-` or `@` stays literal text, so scraped data cannot inject formulas. Use `USER_ENTERED` only if you want formulas to run and dates/numbers to be parsed as if typed.

### Use as an integration after any scraper

Open the Actor you want to export, go to **Integrations > Add integration > this Actor**, then:

1. Set **Dataset** to `{{resource.defaultDatasetId}}` — this passes the finished run's dataset *and* gives this Actor permission to read it.
2. Set the spreadsheet URL (shared with the service account as Editor).
3. Optionally set `mode: upsert` and `keyFields` to keep one row per item across scheduled runs.

The Dataset field matters: this Actor runs with limited permissions and can read only a dataset that arrives through that field. To export an existing dataset by hand, pick it in the same field.

### Use from AI agents / MCP

Because there is no interactive login, an agent can call it directly. Minimal input:

```json
{
  "spreadsheet": "https://docs.google.com/spreadsheets/d/<ID>/edit",
  "sheetName": "Agent output",
  "rows": [{ "id": 1, "summary": "..." }],
  "serviceAccountKey": "<JSON key>"
}
```

The result is in the run's `OUTPUT` record and as one dataset item: `spreadsheetUrl`, `sheetName`, `mode`, `rowsRead`, `rowsWritten`, `rowsUpdated`, `rowsSkippedDuplicate`, `columnsAdded`, `cellsTruncated`, `durationMs`. On failure the same `OUTPUT` record holds `{ error, code }` and the run fails with the same human message.

### Pricing

Pay per event: one `export-run` event per successful export, plus one `rows-1000` event per started 1,000 rows written or updated. Nothing is charged if the run fails or writes no rows. See the pricing tab for current prices.

### Limits (checked against Google's documentation on 2026-11-12)

- **Cells per spreadsheet: 20 million** ([Google Docs Editors Help](https://support.google.com/drive/answer/37603)). The count includes the whole grid of every tab, including empty cells. The Actor stops before writing if the run would pass it.
- **Characters per cell: 50,000** (confirmed against the live API on 2026-11-12: 50,000 accepted, 50,001 rejected). Longer values are truncated and counted in `cellsTruncated`; the run does not fail.
- **API quota: 60 write and 60 read requests per minute per user, 300 per project** ([Sheets API limits](https://developers.google.com/workspace/sheets/api/limits)). Google recommends payloads of about 2 MB at most; the Actor writes in batches below that and retries on 429.
- The Actor reads the target tab once before appending or upserting (to find the last row and existing keys). Very large tabs make that read slow.
- Empty source: nothing is written and nothing is cleared, even in replace mode.

### FAQ

**Do I need to log in to Google?** No. You share your sheet with the service account's address — that is the whole setup.

**Who can see my data?** A service account can read and write only spreadsheets that someone has explicitly shared with its email address. It has no access to the rest of your Drive. With the shared account, the Actor reads the target tab (to find the last row and, for upsert or dedupe, existing keys) and writes your rows; it does not store, copy or log cell contents. Un-share the sheet at any time to end access. If you supply your own key, it is a secret input, is never logged, and is used only to request a short-lived Google access token.

**Shared account or my own?** The shared one needs no setup. Use your own for a private quota or stricter control. Your own key always takes priority.

**My spreadsheet ID is not 44 characters.** That is fine. Any ID of 20 or more letters, digits, `-` and `_` is accepted.

**Why does the run say "not shared"?** Observed live (2026-11-12): a wrong ID gives HTTP 404 "Requested entity was not found"; a spreadsheet the service account may not edit gives HTTP 403 "The caller does not have permission". The Actor maps 404 to "ID wrong or not shared" and 403 to "share it with <email> as Editor". Check the ID, then the share step.

**Does it keep my formatting?** Append and upsert leave existing cells and formatting alone. Replace clears values only, not formatting.

# Actor input Schema

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

The full URL from your browser's address bar, or just the spreadsheet ID (the part between /d/ and /edit). If the URL contains gid=..., that tab is used unless you set Tab name. The prefilled URL is a public demo sheet so you can try a run immediately; replace it with your own.

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

Title of the tab to write to. Created if it does not exist. Leave empty to use the tab from the URL's gid, or the first tab.

## `mode` (type: `string`):

append: add rows after the last non-empty row and never touch existing rows. replace: clear the tab, then write header and rows. upsert: update rows whose key matches (see Key fields) and append the rest.

## `keyFields` (type: `array`):

Column names that identify a row, for example id. Required for upsert. Keys are compared as trimmed text.

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

The dataset to export. Pick it here, or when you attach this Actor as an integration to another Actor put {{resource.defaultDatasetId}} in this field — that is what gives the Actor permission to read the other run's dataset. Leave empty to send your own JSON in Rows.

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

A list of objects, for example \[{"name": "Ann", "age": 30}]. Handy for AI agents and small exports.

## `fields` (type: `array`):

Column names to write, in this order. Leave empty to use all keys found, in first-seen order.

## `flatten` (type: `boolean`):

Nested objects become dot-notation columns (a.b.c). Lists of text or numbers are joined with ", ". Lists of objects become JSON text.

## `dedupeFields` (type: `array`):

Column names. Rows that repeat an earlier source row on these fields are dropped; in append mode, rows already in the sheet with the same values are skipped too.

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

RAW stores everything exactly as given: text starting with =, +, - or @ stays plain text (safe against formula injection). USER_ENTERED lets Google parse values as if typed, so =formulas run and dates convert.

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

Stop after reading this many source rows. Leave empty for no limit.

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

Optional. Leave empty to use the shared service account: share your spreadsheet with sheets-export@sheets-export-actor.iam.gserviceaccount.com as Editor. To use your own service account instead, paste the full contents of its JSON key file here (stored encrypted) and share the spreadsheet with that account's email.

## Actor input object example

```json
{
  "spreadsheet": "https://docs.google.com/spreadsheets/d/1y0zwQfsPKKqbg0qkOWkcdUNNcBvo32F6dTP2pOLhFtc/edit",
  "sheetName": "demo",
  "mode": "replace",
  "rows": [
    {
      "product": "Example A",
      "price": 19.99,
      "inStock": true,
      "details": {
        "color": "blue"
      }
    },
    {
      "product": "Example B",
      "price": 5,
      "inStock": false,
      "details": {
        "color": "red"
      }
    }
  ],
  "flatten": true,
  "valueInputOption": "RAW"
}
```

# Actor output Schema

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

One record per run: spreadsheet URL, tab name, mode, rows read, rows written, rows updated, duplicates skipped, columns added, cells truncated and duration. On failure it holds the error message and code instead.

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

The same summary as one dataset item, for use in integrations and tables.

# 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/1y0zwQfsPKKqbg0qkOWkcdUNNcBvo32F6dTP2pOLhFtc/edit",
    "sheetName": "demo",
    "mode": "replace",
    "rows": [
        {
            "product": "Example A",
            "price": 19.99,
            "inStock": true,
            "details": {
                "color": "blue"
            }
        },
        {
            "product": "Example B",
            "price": 5,
            "inStock": false,
            "details": {
                "color": "red"
            }
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("teal_blacksmith/google-sheets-export").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/1y0zwQfsPKKqbg0qkOWkcdUNNcBvo32F6dTP2pOLhFtc/edit",
    "sheetName": "demo",
    "mode": "replace",
    "rows": [
        {
            "product": "Example A",
            "price": 19.99,
            "inStock": True,
            "details": { "color": "blue" },
        },
        {
            "product": "Example B",
            "price": 5,
            "inStock": False,
            "details": { "color": "red" },
        },
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("teal_blacksmith/google-sheets-export").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/1y0zwQfsPKKqbg0qkOWkcdUNNcBvo32F6dTP2pOLhFtc/edit",
  "sheetName": "demo",
  "mode": "replace",
  "rows": [
    {
      "product": "Example A",
      "price": 19.99,
      "inStock": true,
      "details": {
        "color": "blue"
      }
    },
    {
      "product": "Example B",
      "price": 5,
      "inStock": false,
      "details": {
        "color": "red"
      }
    }
  ]
}' |
apify call teal_blacksmith/google-sheets-export --silent --output-dataset

```

## MCP server setup

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

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/x7AvQqpv8Cb9n5dGp/builds/dzSp5KLrQEPdhACjd/openapi.json
