# Google Sheets Export – Apify Dataset to Sheet, No OAuth (`moriarty_ag/google-sheets-export`) Actor

Send any Apify dataset or JSON array to a Google Sheets tab, automatically after each scraper run. Real append (never overwrites), any tab, no OAuth or browser login, 10M-cell check before writing. Works from AI agents (MCP).

- **URL**: https://apify.com/moriarty_ag/google-sheets-export.md
- **Developed by:** [Moriarty Data Tools](https://apify.com/moriarty_ag) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.50 / 1,000 exported rows

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 Export – Apify Dataset to Sheet, No OAuth

Send any **Apify dataset** (or a JSON array) to a **Google Sheets** tab in one run – from a
scraper, a schedule, an integration or an AI agent.

- **Real append mode** – uses Google's native append, so existing rows are never overwritten.
- **No "App blocked by Google"** – you use your *own* service account. No OAuth screen, no browser login, nothing expires.
- **Works from AI agents (MCP)** – Claude, ChatGPT, Cursor or any MCP client can call it; nothing interactive.
- **Any spreadsheet ID** – paste the full URL or the ID; old 33-character IDs work too.
- **Any tab** – write to any tab by name; it is created if it does not exist.
- **10M-cell check before writing** – if the export would exceed Google's limit, the run stops *before* touching your sheet.
- **Header that grows** – in append mode, new fields are added to the right of your existing header.
- **Readable columns** – nested objects become `address.city`; lists stay in one cell as JSON (no 400-column headers).
- **Pay only for rows written** – $0.50 per 1,000 rows, nothing for failed or rejected exports.

Jump to: [Try it](#try-it-first-preview-mode-no-google-setup) · [Setup](#quick-start-3-minutes-once) ·
[Example](#example-scraper-results-to-a-sheet-every-day) · [Price](#how-much-does-it-cost) ·
[Input](#input) · [AI agents](#use-it-from-an-ai-agent-mcp) · [FAQ](#faq)

### Try it first: preview mode (no Google setup)

Click **Start** with no spreadsheet or key (or tick **Preview only**). Nothing is written to Google:
the dataset shows exactly how your first 20 rows and columns would look – with your
`data`/`datasetId`, or with sample rows. Preview rows are free.

### Quick start (3 minutes, once)

1. Go to [Google Cloud Console](https://console.cloud.google.com/) → create (or pick) a project.
2. **APIs & Services → Library → Google Sheets API → Enable.**
3. **IAM & Admin → Service Accounts → Create service account** (no roles needed).
4. Open it → **Keys → Add key → Create new key → JSON**. A file downloads.
5. Open your spreadsheet → **Share** → paste the service account email
   (`…@….iam.gserviceaccount.com`) → **Editor**.
6. In this Actor, paste the JSON file content into **Google service account key** and the
   sheet URL into **Spreadsheet URL or ID**.

The key is stored as an encrypted secret input and is never written to logs.
It only reaches spreadsheets you explicitly shared with that email.

### Example: scraper results to a sheet, every day

A scraper runs every morning and you want its results added to the tab **Leads**, never
overwriting yesterday's rows.

Input (in the scraper's **Integrations** tab → add this Actor → "Run succeeded"):

```json
{
  "spreadsheet": "https://docs.google.com/spreadsheets/d/1AbC.../edit",
  "serviceAccountJson": "{ \"type\": \"service_account\", ... }",
  "datasetId": "{{resource.defaultDatasetId}}",
  "sheetName": "Leads",
  "mode": "append",
  "fields": ["title", "address.city", "phone", "website", "url"]
}
```

Day 1 writes the header and 120 rows. Day 2 adds 95 rows below them – yesterday's rows stay where
they are. (Without `fields`, a field that appears for the first time on day 3 is added as a new
column to the right of the header.)

| title | address.city | phone | website | url |
|---|---|---|---|---|
| Juniper & Oak Coffee | Austin | (512) 555-0101 | https://juniperoak.example | https://… |
| Lantern Street Roasters | Austin | (512) 555-0102 | https://lanternstreet.example | https://… |

*(Example data is made up.)*

### How much does it cost?

| What | Price |
|---|---|
| Each row written to your sheet | $0.50 per 1,000 rows ($0.0005 per row) |
| Each run start | $0.0005 |
| Platform usage | Included – no compute bill on top |

- 200 rows a day for a month: 6,000 × $0.0005 + 30 starts ≈ **$3.02**.
- Preview runs, failed runs and rejected exports: **no row charges**.
- Set **Maximum cost per run** in the run options: the Actor stops cleanly at that limit.

### Input

| Field | What it does |
|---|---|
| `spreadsheet` | Sheet URL or ID |
| `serviceAccountJson` | Your service account JSON key (secret) |
| `datasetId` | Apify dataset to export (pick it, or `{{resource.defaultDatasetId}}` in an integration) |
| `data` | Or a JSON array of rows (good for agents and small exports) |
| `sheetName` | Tab name (default `Sheet1`, created if missing) |
| `mode` | `append` (default) or `replace` |
| `fields` | Optional list of columns, in order. Nested: `address.city` |
| `includeHeader` | Write field names in row 1 (default on) |
| `flatten` | Nested objects → dotted columns (default on) |
| `flattenArrays` | Also split lists into columns (default off: lists stay as JSON in one cell) |
| `createSheet` | Create the tab if missing (default on) |
| `maxRows` | Stop after N rows |
| `dryRun` | Preview how rows will look, write nothing, not charged |

### Output

The run's `OUTPUT` record (also one summary row in the dataset):

```json
{ "spreadsheetUrl": "...", "sheetName": "Leads", "mode": "append",
  "rowsWritten": 95, "columns": ["title", "address.city", "phone", "website", "url"],
  "tabCreated": false, "stoppedByCostLimit": false }
```

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

Add Apify's MCP server with this Actor as a tool:

```json
{ "mcpServers": { "apify": { "url": "https://mcp.apify.com?tools=moriarty_ag/google-sheets-export" } } }
```

An agent holding rows can send them straight to a sheet:
`{"spreadsheet": "...", "serviceAccountJson": "...", "data": [{"name": "Ada", "city": "London"}], "sheetName": "Contacts"}`.
No browser login is ever needed, so it works unattended.

### Switching from another Google Sheets Actor?

| If you saw this elsewhere | Here |
|---|---|
| "App blocked by Google" / "Cannot authorize Google Drive" | No OAuth at all: your own service account key |
| Append mode overwrote my data | Native Google append (`INSERT_ROWS`): never overwrites |
| "Spreadsheet ID must be 44 characters" | Any URL or ID, any length |
| Can't write to a tab other than the first | `sheetName` – created if missing |
| "You reached the max limit of cells" mid-run | Checked before writing; nothing is touched if it won't fit |
| Hundreds of `field.0.x` columns | Lists stay in one cell unless you ask otherwise |
| Doesn't run from Claude / MCP | Nothing interactive – agents can run it |

### FAQ

**How do I send Apify results to Google Sheets automatically?**
On your scraper (or its saved task) open **Integrations** → add this Actor → start when the run
succeeds → set `datasetId` to `{{resource.defaultDatasetId}}`. Every successful run then appends
to your sheet.

**How do I append to an existing sheet without overwriting it?**
Use `mode: append` (the default). Rows go below the last row; your header is kept and extended
if new fields appear.

**How do I replace the sheet every time (a fresh snapshot)?**
Use `mode: replace`. The tab is cleared first, then the new rows are written.

**Why a service account instead of "Sign in with Google"?**
OAuth apps get blocked by Google, expire, and need a browser – useless for schedules and agents.
A service account works forever, only sees sheets you share with it, and you can revoke it in one
click in Google Cloud.

**How do I export only some columns, in my order?**
List them in `fields`, e.g. `title`, `price`, `address.city`.

**Is it safe to paste my key?**
It's a secret input: stored encrypted by Apify, never logged, only sent to Google. The key only
works on spreadsheets you shared with its email. If in doubt, delete the key in Google Cloud and
create a new one.

**Need the other direction?**
[Google Sheets Import](https://apify.com/moriarty_ag/google-sheets-import) reads any tab –
including private sheets – into a dataset with the same key.

### Common errors (and the fix the Actor tells you)

| Message | Fix |
|---|---|
| No access to the spreadsheet | Share the sheet with the service account email as Editor |
| Google Sheets API is not enabled | Enable it in APIs & Services → Library |
| Not a service-account key | Download a **JSON key** of a service account, not an OAuth client |
| Needs about N cells | Fewer `fields`, a `maxRows`, or a new spreadsheet |
| Could not open dataset | Pick the dataset with the picker (that grants read access) |

### Limits

- Google Sheets: 10,000,000 cells per spreadsheet, 50,000 characters per cell
  (longer values are truncated and marked `…[truncated]`).
- Google API quotas apply to *your* project; the Actor retries automatically on rate limits.

Found a bug? Open an issue on the **Issues** tab with the input you used (without your key).

# Actor input Schema

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

Paste the whole Google Sheets address bar, or just the ID. Any ID length works. Leave empty to only preview.

## `serviceAccountJson` (type: `string`):

Content of the JSON key of YOUR Google Cloud service account. Then share the spreadsheet with the service account email as Editor. Stored encrypted; never logged. See README for a 3-minute setup. Leave empty to only preview.

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

Pick the Apify dataset to export (e.g. from another Actor run), or pass its ID via API/integration. Leave empty if you use 'data'.

## `data` (type: `array`):

Rows to write, as a JSON array of objects. Handy for AI agents and small exports. Ignored if empty.

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

Tab to write to. Created automatically if it does not exist.

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

append = add rows after the existing ones (never overwrites). replace = clear the tab first.

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

Only these fields, in this order. Nested fields use dots, e.g. 'address.city'. Empty = all fields.

## `includeHeader` (type: `boolean`):

Write field names in row 1. In append mode, new fields are added to the right of the existing header.

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

Turn {"a":{"b":1}} into a column 'a.b'. If off, nested objects are written as JSON text.

## `flattenArrays` (type: `boolean`):

Off (recommended): lists are written as JSON text in one cell. On: each list item gets its own column (tags.0, tags.1…), which can create hundreds of columns on crawler data.

## `createSheet` (type: `boolean`):

Create the tab automatically if it does not exist. If off, the run fails when the tab is missing.

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

Stop after this many rows. Empty = no limit.

## `dryRun` (type: `boolean`):

Show in the dataset how the first 20 rows and columns would look, without writing to Google Sheets. Also used automatically when no spreadsheet or key is given. Rows are not charged.

## Actor input object example

```json
{
  "sheetName": "Sheet1",
  "mode": "append",
  "includeHeader": true,
  "flatten": true,
  "flattenArrays": false,
  "createSheet": true,
  "dryRun": false
}
```

# Actor output Schema

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

No description

# 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 = {};

// Run the Actor and wait for it to finish
const run = await client.actor("moriarty_ag/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 = {}

# Run the Actor and wait for it to finish
run = client.actor("moriarty_ag/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 '{}' |
apify call moriarty_ag/google-sheets-export --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,moriarty_ag/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/GyzpFj8g2aRc8TChG/builds/8XQZ0Ng8lgc1ipHo9/openapi.json
