# Google Sheets Sync — Apify Dataset Export, Upsert & Import (`structmint/google-sheets-dataset-sync`) Actor

Sync Apify Datasets to Google Sheets reliably without OAuth crashes. Supports Service Account, 1-click Apps Script & public import, upsert, JSON flattening & 429 retries. $0.005/sync + $0.10/1,000 rows · Failed runs free · AI Agent & MCP ready.

- **URL**: https://apify.com/structmint/google-sheets-dataset-sync.md
- **Developed by:** [StructMint](https://apify.com/structmint) (community)
- **Categories:** Integrations, Automation, Developer tools
- **Features:** Limited permissions
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $3.00 / 1,000 sheet sync completed

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/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 Sync — Reliable Apify Dataset Export, Upsert & Import

Sync any **Apify Dataset**, JSON array, or CSV directly to **Google Sheets** — or import any public or private **Google Sheet** into a typed Apify Dataset & `OUTPUT.csv` — without broken OAuth popups, nested JSON write crashes, or HTTP 429 quota failures.

Built for **high reliability at 256–512 MB RAM** under `LIMITED_PERMISSIONS`:

- **Zero-Auth Public Import (1-Click Ready):** Click **Start** immediately to read any public or anyone-with-link Google Sheet into structured JSON Dataset rows and `OUTPUT.csv`.
- **Service Account RS256 OAuth2:** Direct Google Sheets API v4 reads and writes with automatic missing-tab creation, 5,000-row chunked batches, and exponential backoff on HTTP 429 / 503.
- **1-Click Google Apps Script Mode (Zero GCP Console):** Paste a 25-line Apps Script into your sheet and export immediately without creating a Google Cloud project.
- **Upsert Without Duplicates + Nested JSON Flattening:** Update matching rows in-place by `primaryKeyColumn`, skip unchanged rows free, flatten nested objects (`pricing.amount`), and skip previously synced rows across schedules with **Watch Mode**.

***

### Transparent Pay-Per-Event Pricing

**Failed runs and Dry Runs are free (`$0` sync and row charges).** Skipped, duplicate, unchanged upsert, and Watch Mode rows incur `$0` row charges.

| Event | Description | FREE | BRONZE | SILVER | GOLD+ |
| :--- | :--- | ---: | ---: | ---: | ---: |
| `apify-actor-start` | One-time container start fee | `$0.00005` | `$0.00005` | `$0.00005` | `$0.00005` |
| `sheet-sync-completed` | Charged once per successful sync (`$0` on failure) | `$0.0050` | `$0.0040` | `$0.0035` | `$0.0030` |
| `row-synced` | Per imported or written row (`$0` on skipped/unchanged) | `$0.00010` | `$0.00008` | `$0.00007` | `$0.00006` |

#### Exact Cost Examples (FREE Tier Ceiling)

- **Sync 1,000 rows to or from Google Sheets:** `$0.005` + `1,000 × $0.0001` = **`$0.105`** (`$0.084` on BRONZE, `$0.063` on GOLD+)
- **Sync 10,000 rows (chunked in two 5,000-row batches):** `$0.005` + `10,000 × $0.0001` = **`$1.005`**
- **Scheduled Watch Mode run with 0 changed rows:** `$0.005` + `0` row charges = **`$0.005`**
- **Failed run (bad sheet ID, missing permission, or dry run):** **`$0.00`** sync/row charge

***

### 3-Step Quick Start

#### Option A — Import Any Public Google Sheet (Zero Setup)

1. Keep **Operation Mode** set to `import_public`.
2. Paste any public Google Sheets URL (or Spreadsheet ID) and optional `sheetName`.
3. Click **Start** — receive clean typed JSON rows in the **Dataset** tab and a downloadable **`OUTPUT.csv`** in Key-Value Store.

```json
{
  "operationMode": "import_public",
  "spreadsheetUrlOrId": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit",
  "sheetName": "Class Data",
  "inferTypes": true,
  "maxRows": 1000
}
```

#### Option B — Export & Upsert Apify Dataset via Google Service Account

1. Share your Google Sheet with your Google Cloud Service Account `client_email` as **Editor** (or **Viewer** for `import_service_account`).
2. Set `operationMode: "export_service_account"`, pick your **Source Apify Dataset** (or wire `{{resource.defaultDatasetId}}` via Apify **Add integration**), and paste `serviceAccountJson` (encrypted at rest; never logged).
3. Choose `writeMode`: `"append"`, `"replace"`, or `"upsert"` (with `primaryKeyColumn`, e.g. `"sku"` or `"id"`). Missing tabs are created automatically.

```json
{
  "operationMode": "export_service_account",
  "spreadsheetUrlOrId": "https://docs.google.com/spreadsheets/d/<YOUR_SHEET_ID>/edit",
  "sheetName": "Catalog",
  "writeMode": "upsert",
  "primaryKeyColumn": "sku",
  "sourceDatasetId": "{{resource.defaultDatasetId}}",
  "flattenNestedObjects": true,
  "arrayJoinDelimiter": ", ",
  "watchMode": true,
  "onlyNew": true,
  "watchStateKey": "daily-catalog-sync"
}
```

#### Option C — 1-Click Apps Script Export (Zero GCP Console)

1. Open your Google Sheet → **Extensions → Apps Script**, paste the 25-line template below, and click **Deploy → New deployment → Web app** (*Execute as: Me*, *Who has access: Anyone*).
2. Copy the `https://script.google.com/macros/s/.../exec` Web App URL into `appsScriptUrl` and set `operationMode: "export_apps_script"`.
3. Optionally set matching `webhookSecret` in both the script and Actor input, then click **Start**.

```javascript
function doPost(e) {
  const SECRET = ""; // Optional: match webhookSecret in Actor input
  const p = JSON.parse(e.postData.contents);
  if (SECRET && p.webhookSecret !== SECRET) {
    return ContentService.createTextOutput(JSON.stringify({ ok: false, error: "Unauthorized" })).setMimeType(ContentService.MimeType.JSON);
  }
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sh = ss.getSheetByName(p.sheetName || "Apify Data") || ss.insertSheet(p.sheetName || "Apify Data");
  if (p.writeMode === "replace" && p.isFirstBatch) sh.clearContents();
  if (sh.getLastRow() === 0 && p.headers.length) sh.appendRow(p.headers);
  const headers = sh.getRange(1, 1, 1, Math.max(sh.getLastColumn(), p.headers.length)).getValues()[0];
  let inserted = 0, updated = 0;
  if (p.writeMode === "upsert" && p.primaryKeyColumn) {
    const pkCol = headers.indexOf(p.primaryKeyColumn);
    const vals = sh.getLastRow() > 1 && pkCol >= 0 ? sh.getRange(2, pkCol + 1, sh.getLastRow() - 1, 1).getValues() : [];
    const byKey = Object.fromEntries(vals.map((r, i) => [String(r[0]).trim(), i + 2]).filter(([k]) => k));
    const add = [];
    for (const r of p.rows) {
      const k = pkCol >= 0 ? String(r[pkCol] ?? "").trim() : "";
      if (k && byKey[k]) { sh.getRange(byKey[k], 1, 1, r.length).setValues([r]); updated++; } else add.push(r);
    }
    if (add.length) { sh.getRange(sh.getLastRow() + 1, 1, add.length, add[0].length).setValues(add); inserted = add.length; }
  } else if (p.rows.length) { sh.getRange(sh.getLastRow() + 1, 1, p.rows.length, p.rows[0].length).setValues(p.rows); inserted = p.rows.length; }
  return ContentService.createTextOutput(JSON.stringify({ ok: true, inserted, updated })).setMimeType(ContentService.MimeType.JSON);
}
```

***

### Native Apify `Add integration` & Scheduled Pipelines

Attach this Actor directly to the **Integrations → Add integration** tab of any upstream scraper without writing glue code:

- **`LIMITED_PERMISSIONS` safe:** `sourceDatasetId` declares `resourceType: "dataset"` with `resourcePermissions: ["READ"]`, so Apify grants read-only access to the triggering run's private dataset automatically.
- **Automatic webhook fallback:** Map `"sourceDatasetId": "{{resource.defaultDatasetId}}"`, or leave source fields empty to automatically read `payload.resource.defaultDatasetId`. Explicit inputs always take precedence.
- **Incremental Watch Mode:** Enable `watchMode: true` and `onlyNew: true` with a stable `watchStateKey` (stored in Named Key-Value Store `structmint-gsheets-watch-v1`) so recurring schedules only sync new or modified rows.

***

### AI Agents & MCP

Connect this Actor directly to Claude, Cursor, Windsurf, or any MCP-compatible AI agent using the Apify MCP Server URL:

```text
https://mcp.apify.com?tools=structmint/google-sheets-dataset-sync
```

AI agents can:

- Read structured JSON rows from any public or private Google Sheet (`import_public` / `import_service_account`)
- Write inline `records` arrays or upstream Apify Datasets into Google Sheets with automatic nested JSON flattening and `upsert` deduplication
- Preview schema flattening and download `OUTPUT.csv` risk-free using `dryRun: true`

***

### Output Artifacts

Every run produces:

1. **Default Dataset (`results`):** Clean typed spreadsheet rows (on import modes) or a structured sync receipt with row counts, batch counts, and column list (on export modes).
2. **`OUTPUT` (Key-Value Store JSON):** Full run summary, diagnostics, sample rows, billing breakdown, and warnings.
3. **`OUTPUT.csv` (Key-Value Store CSV):** Normalized RFC 4180 CSV snapshot of synced rows.

# Actor input Schema

## `operationMode` (type: `string`):

Select import_public for zero-auth public Google Sheet import (ready to click Start immediately), export_service_account or import_service_account for Google Service Account OAuth2, or export_apps_script for zero-GCP-Console webhook export.

## `spreadsheetUrlOrId` (type: `string`):

Full Google Sheets URL (https://docs.google.com/spreadsheets/d/<ID>/edit) or raw Spreadsheet ID. Required for import_public, import_service_account, and export_service_account. Optional for export_apps_script when your Apps Script targets the bound spreadsheet.

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

Target tab name (for example 'Class Data', 'Catalog', or 'Apify Data'). In export modes, missing tabs are created automatically. Leave empty to use the first sheet or the gid extracted from the URL.

## `gid` (type: `string`):

Optional numeric tab GID (for example '0' from #gid=0). Used for import_public when sheetName is empty; automatically extracted from spreadsheetUrlOrId if present.

## `writeMode` (type: `string`):

Controls how exported rows are written to Google Sheets: append adds rows at the bottom, replace clears the tab and writes fresh rows, and upsert updates existing rows matching primaryKeyColumn in-place and appends new rows without duplicates.

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

When enabled on export modes, reads your Apify Dataset / records, flattens nested JSON, applies deduplication/Watch Mode, and generates OUTPUT.csv without writing to Google Sheets ($0 sync and row charges).

## `sourceDatasetId` (type: `string`):

Apify Dataset to export into Google Sheets. Uses Apify's native Dataset Resource Picker with READ-only scope under LIMITED_PERMISSIONS. In Actor-to-Actor Add integration, map {{resource.defaultDatasetId}} or leave blank to use automatic webhook payload.resource.defaultDatasetId fallback.

## `records` (type: `array`):

Optional inline JSON array of objects to export directly into Google Sheets (ideal for AI agents, MCP calls, n8n/Make workflows, or quick export tests).

## `sourceUrl` (type: `string`):

Optional public HTTPS URL returning a JSON array, { "items": \[...] }, NDJSON, or CSV/TSV dataset to export into Google Sheets. Private, loopback, and metadata network ranges are blocked.

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

Maximum number of rows to import or export in a single run (1 to 250,000).

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

Full Google Cloud Service Account JSON key (containing client_email and private_key). Share your Google Sheet with the Service Account email as Editor (export) or Viewer (import). Encrypted at rest by Apify and never logged or written to output.

## `appsScriptUrl` (type: `string`):

Deployed Google Apps Script Web App URL (https://script.google.com/macros/s/.../exec) for zero-GCP-Console export_apps_script mode. Strictly restricted to HTTPS script.google.com and script.googleusercontent.com.

## `webhookSecret` (type: `string`):

Optional shared secret sent in the JSON body (webhookSecret) to your Apps Script Web App to prevent unauthorized writes. Encrypted at rest and never logged.

## `primaryKeyColumn` (type: `string`):

Column name used to match existing rows when writeMode is 'upsert' (for example 'id', 'sku', 'url', or 'orderId'). Matching rows are updated in-place; unchanged rows are skipped free; new keys are appended.

## `deduplicateByColumn` (type: `string`):

Optional column name used to remove duplicate rows within this run before pushing to Dataset or writing to Google Sheets.

## `flattenNestedObjects` (type: `boolean`):

When enabled (recommended), recursively flattens nested objects into dot-notation columns (for example pricing.amount, specs.weight) so Google Sheets writes never fail on nested JSON.

## `arrayJoinDelimiter` (type: `string`):

Delimiter used when joining primitive arrays (strings/numbers/booleans) into a single cell (for example ', ' or ' | '). Arrays of objects are safely serialized as compact JSON.

## `columns` (type: `array`):

Optional ordered list of column names to keep. Leave empty to automatically include all discovered columns in stable order.

## `excludeColumns` (type: `array`):

Optional list of column names to drop before writing to Google Sheets or pushing to the Apify Dataset.

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

Controls whether Google Sheets parses written cell values (numbers, dates, formulas) via USER_ENTERED or stores raw literal strings via RAW.

## `inferTypes` (type: `boolean`):

When importing from a public Google Sheet, automatically convert clean numeric and boolean cell values into JSON numbers and booleans while preserving leading-zero strings (such as postal codes or IDs) as strings.

## `chunkSize` (type: `integer`):

Number of rows written per Google Sheets API batch request (50 to 5,000; automatically capped at 1,000 for Apps Script Web App requests).

## `maxRetries` (type: `integer`):

Number of automatic retry attempts with exponential backoff when Google Sheets returns HTTP 429 rate-limit or 5xx transient errors.

## `watchMode` (type: `boolean`):

Persists synced row fingerprints in a user-scoped Named Key-Value Store (structmint-gsheets-watch-v1, 90-day retention) so scheduled runs track previously synced data.

## `onlyNew` (type: `boolean`):

Used with watchMode=true. Skips unchanged rows already synced in prior runs with $0 row charges. Modified rows are still synced.

## `watchStateKey` (type: `string`):

Stable namespace key separating watch checkpoints for different spreadsheets or recurring schedules.

## `maxTotalChargeUsd` (type: `number`):

Optional hard spend cap in USD for this run. Also automatically honors Apify's run-level maxTotalChargeUsd.

## Actor input object example

```json
{
  "operationMode": "import_public",
  "spreadsheetUrlOrId": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit",
  "sheetName": "Class Data",
  "gid": "",
  "writeMode": "append",
  "dryRun": false,
  "maxRows": 50000,
  "primaryKeyColumn": "",
  "deduplicateByColumn": "",
  "flattenNestedObjects": true,
  "arrayJoinDelimiter": ", ",
  "columns": [],
  "excludeColumns": [],
  "valueInputOption": "USER_ENTERED",
  "inferTypes": true,
  "chunkSize": 5000,
  "maxRetries": 4,
  "watchMode": false,
  "onlyNew": true,
  "watchStateKey": "default-gsheets-watch"
}
```

# Actor output Schema

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

No description

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

No description

## `csv` (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 = {
    "operationMode": "import_public",
    "spreadsheetUrlOrId": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit",
    "sheetName": "Class Data"
};

// Run the Actor and wait for it to finish
const run = await client.actor("structmint/google-sheets-dataset-sync").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 = {
    "operationMode": "import_public",
    "spreadsheetUrlOrId": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit",
    "sheetName": "Class Data",
}

# Run the Actor and wait for it to finish
run = client.actor("structmint/google-sheets-dataset-sync").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 '{
  "operationMode": "import_public",
  "spreadsheetUrlOrId": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit",
  "sheetName": "Class Data"
}' |
apify call structmint/google-sheets-dataset-sync --silent --output-dataset

```

## MCP server setup

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

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/5MJmk7ogV0xPkOkkd/builds/vV6uVh8IgyRARRJ1a/openapi.json
