# Sheets Sync Pro (`master_invictus/sheets-sync-pro`) Actor

Reliable export of datasets/JSON to Google Sheets and import of sheets into datasets, with service-account auth.

- **URL**: https://apify.com/master_invictus/sheets-sync-pro.md
- **Developed by:** [Frank Nagy](https://apify.com/master_invictus) (community)
- **Categories:** Integrations, Automation
- **Security:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per event

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 Import & Export – Sheets Sync Pro

Export any Apify dataset or JSON to a Google Sheet (append, replace, or upsert), or import a sheet into a dataset. Private sheets use the **official Google Sheets API v4** with **your own service account** (recommended) or an OAuth access token. There is no OAuth pop-up and no shared token store.

A sheet shared as **anyone with the link** can be imported with no credentials (`import-public`). That mode is the default, so the Apify Store health run succeeds without secrets.

### Why another Sheets Actor? Incumbent failure analysis

The store leader `lukaskrivka/google-sheets` has 812 users/30d and 4.81★, but **only 49% of runs succeeded** in the last 30 days: 40,940 succeeded vs 42,605 failed out of 83,622 runs (public store API, 2026-10-13). From its public README and issue titles:

| Incumbent failure mode (evidence) | How this Actor handles it |
|---|---|
| OAuth connect breaks: issues "Cannot authorize Google Drive", "Doesn't allow to Auth in Google", "Getting spreadsheet metadata failed with error invalid_request"; a deprecated tokens store | Stateless auth: a service-account JWT signed in code, or a raw OAuth token. No token store, no browser consent step. Works in schedules, API calls and MCP/agent runs (issue: "unable to run this actor through Claude MCP") |
| README: exceeding 60 reads/updates per minute makes "the actor run fail, and no data will be imported" | Retries every call on 429/5xx/network errors with exponential backoff and jitter, and honours `Retry-After` (default 6 retries) |
| "You reached the max limit of 5000000 cells" (an outdated limit; Google's is now 10M), discovered mid-run | The cell budget is checked **before writing** and nothing is written if it would overflow. `columnsMapping` + `onlyMappedColumns` shrink exports |
| Generic "The main function of the Actor threw an exception" / "Actor keeps throwing exception" | Every error says what failed **and what to do**: the exact `client_email` to share the sheet with, enabling the Sheets API, the right ID, a bad range or tab (lists existing tabs), a mangled private key (lost `\n` line breaks), an expired token |
| Rewrites the whole sheet on every run; locale-dependent parsing ("1,1" vs "1.1") | Append writes only new rows. Replace **writes first, then clears leftover rows**, with a backup in the KV record `BACKUP`. `valueInputOption=RAW` by default, so values are stored exactly |
| Silent "success" when nothing happened | **Fails loudly on 0 rows** (empty dataset, empty sheet, or every row a duplicate). `allowEmpty=true` opts out for incremental schedules |
| Wrong tab name ("Importing to a Different Sheet Name") | `sheetName` is explicit, and missing tabs are created on export |

### Modes

- `import-public` (default, v0.4): reads a spreadsheet shared as **Anyone with the link**. It does not call the Sheets API and ignores `serviceAccountJson` / `oauthAccessToken`. The download URL is `https://docs.google.com/spreadsheets/d/{spreadsheetId}/export?format=csv&gid={gid}`. `gid` is the tab id (usually `0` for the first tab); `sheetName` is not used. The first row is headers. `columnsMapping`, `dedupeBy`, `limit`, and `allowEmpty` work as in `import`. The default spreadsheet is Google's public Class Data sample (`1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms`).
- `export-append`: adds rows below existing data. It keeps the existing column order and appends new columns at the end. `dedupeBy` skips rows whose key already exists in the sheet.
- `export-replace`: overwrites the tab. The old content is backed up first.
- `export-upsert` (v0.2): updates rows in place by `upsertKey` (one or more columns). A row whose key matches a sheet row overwrites that row. Fields missing from the input keep their current sheet value. Unmatched rows are appended, and new columns are added at the end. Only changed rows are written, and unchanged rows are counted, not rewritten.
- `import`: reads a private `sheetName`\[!`range`] through the Sheets API and treats the first row as headers. `columnsMapping` renames headers; `dedupeBy` and `limit` are supported. Output goes to the dataset. Requires a service account or OAuth token, and the sheet must be shared with that identity.

v0.4 keeps the v0.2 export behavior and the v0.3 `dedupeBy` coercion. The default mode is now `import-public` so a run that uses only schema defaults and prefills does not need Google credentials. Pass `mode` explicitly for export or private import.

`dedupeBy` is a string or an array of column names. `["id","city"]` and the comma-separated string `"id,city"` select the same columns. Empty, missing, or whitespace-only values skip deduplication.

**Per-row error reporting (v0.2):** export modes return `rowErrors[]` in the `OUTPUT` record and push one `type: "row-error"` dataset item per problem: `inputRow`, `key`, `column`, `severity` (`error` = row skipped, `warning` = written with changes such as truncation) and `error`. Upsert flags rows with a missing key or a duplicate key in the input. The run still succeeds when other rows were written.

v0.2 is backward-compatible: existing inputs and modes behave as before, and the new output fields are additive.

v0.3 keeps that compatibility and accepts `dedupeBy` as a string or an array inside the core runner (the same comma-separated coercion `main.js` already applies).

Nested objects are flattened with `/` (`geo/lat`, `tags/0`). Cells longer than 50,000 characters are truncated with a marker instead of failing the batch.

### Setup (2 minutes, private sheets only)

Skip this for `import-public`. The default run does not need a Google account.

1. Google Cloud Console: create or choose a project, then enable **Google Sheets API**.
2. IAM → Service accounts → Create → Keys → Add key → JSON. Paste the file into `serviceAccountJson` (it is stored as a secret).
3. Share your spreadsheet with the service account's `client_email` (Editor for export, Viewer for import).

### Pricing (pay per event)

| Event | Price |
|---|---|
| `run-started`: custom flat event, charged once per run after a successful import or export. A failed run is not billed (not Apify's memory-scaled `apify-actor-start`) | $0.005 |
| `row-batch`: per started block of 1,000 rows written or read | $0.002 |

When publishing, configure `run-started` as a custom event. Do not enable the synthetic start event, which is priced per GB of memory. See `PRICING.md`.

***

Built and maintained by **MasterInvictus**.

# Actor input Schema

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

import-public reads a sheet shared as anyone with the link via the public CSV export and needs no credentials. The other modes use the Sheets API.

## `spreadsheetId` (type: `string`):

The ID from the sheet URL (between /d/ and /edit). The default is Google's public Class Data sample, shared as anyone with the link.

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

Tab to read/write for API modes; created on export if missing. import-public uses gid instead.

## `gid` (type: `integer`):

Tab id for import-public (the gid query on /export?format=csv). The first tab is usually 0. Ignored by API modes.

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

Optional A1 range for import, e.g. A1:F500.

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

Paste the whole JSON key file. Share the sheet with its client_email.

## `oauthAccessToken` (type: `string`):

Use instead of a service account. Expires after ~1 hour.

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

Apify dataset to export.

## `rawData` (type: `array`):

Array of objects to export instead of a dataset.

## `columnsMapping` (type: `object`):

Rename fields/headers: {"source": "Target"}.

## `onlyMappedColumns` (type: `boolean`):

Keep only columns present in the mapping.

## `upsertKey` (type: `array`):

Column(s) identifying a row, e.g. id. Matching sheet rows are updated in place (columns missing from the input keep their sheet value); others are appended. A comma-separated string is also accepted via API.

## `dedupeBy` (type: `array`):

String or array of column names. Skip rows whose values in these fields already exist. An array such as \["id", "city"] and a comma-separated string such as "id,city" are equivalent. Empty or missing values skip deduplication.

## `limit` (type: `integer`):

Max rows to read/write.

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

RAW stores values exactly; USER_ENTERED parses like typing.

## `batchSize` (type: `integer`):

Rows per API write.

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

Retries on 429/5xx with backoff.

## `allowEmpty` (type: `boolean`):

Do not fail when 0 rows are processed.

## Actor input object example

```json
{
  "mode": "import-public",
  "spreadsheetId": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
  "sheetName": "Sheet1",
  "gid": 0,
  "onlyMappedColumns": false,
  "valueInputOption": "RAW",
  "maxRetries": 6,
  "allowEmpty": false
}
```

# Actor output Schema

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

Rows read from the sheet (import mode only; columns follow the sheet headers).

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

OUTPUT record: rows written/read, duplicates skipped, retries.

# 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 = {
    "mode": "import-public",
    "spreadsheetId": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
    "gid": 0
};

// Run the Actor and wait for it to finish
const run = await client.actor("master_invictus/sheets-sync-pro").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 = {
    "mode": "import-public",
    "spreadsheetId": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
    "gid": 0,
}

# Run the Actor and wait for it to finish
run = client.actor("master_invictus/sheets-sync-pro").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 '{
  "mode": "import-public",
  "spreadsheetId": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
  "gid": 0
}' |
apify call master_invictus/sheets-sync-pro --silent --output-dataset

```

## MCP server setup

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

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/NCUk8Bh0JFvvBwSby/builds/AM3LifPDFTaff5mef/openapi.json
