# Google Sheets Sync: Append, Upsert & Dedupe Any Dataset (`panthalus/google-sheets-sync`) Actor

Export any Apify dataset or JSON to Google Sheets. Append that really appends, upsert by key, dedupe, auto-added columns, 10M-cell guard and plain-English errors. Works as an integration after any scraper. Uses your own service account.

- **URL**: https://apify.com/panthalus/google-sheets-sync.md
- **Developed by:** [Panthalus](https://apify.com/panthalus) (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 $0.10 / 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 Sync: Append, Upsert & Dedupe Any Dataset

![Google Sheets Sync: datasets into Google Sheets](https://api.apify.com/v2/key-value-stores/OUAKECfhX5Svhoo26/records/banner-sheets-sync)

**Send any Apify dataset or JSON straight into a Google Sheet, reliably.** Append rows that really get appended, update existing rows by key (upsert), skip duplicates, and add new columns on the fly. Runs on its own or as an integration after any scraper. It can also read a tab back into a dataset.

It uses **your own Google service account**, so no third-party app ever gets access to your Google Drive.

### What it does

| Mode | What happens |
|---|---|
| `append` | Adds rows under the existing data. Existing rows are never touched. |
| `replace` | Clears the tab and writes the new data. If the input is empty, the tab is left as it is, so an empty scraper run can't wipe your sheet. |
| `upsert` | Rows whose `keyColumns` match an existing row update that row. Every other row is appended. |
| `read` | Copies a tab into the run's dataset. The header row becomes the field names. |

Options in every write mode: **dedupe** (skip rows already in the sheet or repeated in this run), **columns to export** (pick and order the fields), **flattening** (`address.city` columns, arrays joined with `, `), **max rows**, **rollover to new tabs** and **dry run** (shows what would change and writes nothing).

### Why it's reliable

- **Append really appends.** New rows always go below the last row. Nothing gets overwritten or replaced.
- **Upsert by key.** You can use one key (`url`) or several (`sku` + `store`). Only the cells that actually changed are written. Your own formula columns, notes and manual edits in other columns are kept. Unchanged rows are skipped, and you don't pay for them.
- **Columns are added automatically.** The header row is created on the first write. When a later run has new fields, they become new columns at the right. The existing column order is kept, so rows never end up in the wrong columns.
- **It checks the 10M-cell limit before writing.** Google caps a spreadsheet at 10,000,000 cells, counting all tabs and empty grid cells too. The Actor counts the cells before every write. If the next batch wouldn't fit, it writes the rows that do fit, stops cleanly, and the run summary says how many rows were left out. You don't get a "You reached the max limit" crash halfway through. New tabs are sized exactly, so no cells are wasted.
- **Rollover tabs.** Set `maxRowsPerTab` and data continues in `<Tab> (2)`, `<Tab> (3)`, and so on. Upsert and dedupe search across all of these tabs.
- **It respects Google's limits.** Writes go in batches of up to 1,000 rows (about 2 MB) per request. A client-side rate limiter keeps it under Google's 60 requests per minute per user. Errors 429, 500 and 503 are retried with exponential backoff and jitter, and Google's `Retry-After` header is honoured. A write is never retried blindly if Google might already have saved it.
- **Errors tell you what to do.** Examples:
  - *"The service account can't edit this spreadsheet. In Google Sheets click Share, add sheets-bot@your-project.iam.gserviceaccount.com as Editor..."*
  - *"The Google Sheets API is not enabled in Google Cloud project your-project. Open https://console.cloud.google.com/apis/library/sheets.googleapis.com?project=your-project, click Enable..."*
  - Wrong spreadsheet ID, an Excel file instead of a Google Sheet, a malformed or deleted key: each has its own plain-English message.
- **Safe values.** By default text is written as-is (`RAW`), so a scraped value like `=IMPORTXML(...)` is stored as text and never runs as a formula. Integers longer than 15 digits are written as text so no digits are lost. Cells over Google's 50,000-character limit are truncated, and the run reports how many.

### Setup: Google service account (about 5 minutes, one time)

1. Open **https://console.cloud.google.com**. In the project picker in the top bar, choose **New Project**, give it a name, and click **Create**. You can also use an existing project.
2. Go to **APIs & Services > Library**, search for **Google Sheets API**, open it and click **Enable**.
3. Go to **IAM & Admin > Service Accounts** and click **+ Create service account**. Enter a name (e.g. `sheets-sync`), then click **Create and continue**. The service account doesn't need any project role, so you can skip the optional steps. Click **Done**.
4. Click the new service account, open the **Keys** tab and choose **Add key > Create new key > JSON > Create**. A `.json` file downloads. Keep it private.
5. Open your spreadsheet and click **Share**. Paste the service account's email (the `client_email` value in the JSON file, ending in `.iam.gserviceaccount.com`), choose **Editor**, untick **Notify people**, and click **Share**.
6. In this Actor's input, paste the **whole content** of the JSON file into **Service account key (JSON)**. The field is a secret input, so Apify stores it encrypted.

Tip: run once with **Dry run** on. It checks the key, the sharing and your data, and shows exactly what would be written.

### Use it as an integration after any scraper

1. Open the scraper (any Actor or task) in Apify Console and go to its **Integrations** tab.
2. Click **Add integration**, choose **Connect Actor or Task**, and pick **Google Sheets Sync**.
3. Fill in the static part of the input: spreadsheet URL, service-account key, tab name, mode (e.g. `upsert` with `keyColumns: ["url"]`). **Leave the data-source fields empty.**
4. Choose the event **Run succeeded** and save.

After every successful scraper run, this Actor gets the run's details (`payload.resource.defaultDatasetId`) and exports that run's dataset. You don't need to copy any IDs. If you prefer to be explicit, set **Dataset** to `{{resource.defaultDatasetId}}` in the integration input.

### Input

| Field | Description |
|---|---|
| `spreadsheetId` | Spreadsheet URL or ID (required). If the URL ends in `#gid=...`, that tab is used when `sheetName` is empty. |
| `serviceAccountKey` | Full JSON key of your service account (secret input). |
| `sheetName` | Tab to use. Created if it doesn't exist. Default: the tab in the URL, otherwise the first tab. |
| `mode` | `append` (default), `replace`, `upsert` or `read`. |
| `keyColumns` | Columns that identify a row. Required for `upsert`. With `dedupe` in `append` mode, only rows with new keys are added. |
| `dedupe` | Skip rows already in the sheet and rows repeated in this run. Without keys, a row counts as a duplicate when all its values match. |
| `datasetId` / `items` / `jsonUrl` | The data source; pick one. Leave all three empty when the Actor runs as an integration. `jsonUrl` accepts a JSON array, `{items/data/results: [...]}` or JSON Lines. |
| `fields` | Columns to export, in this order. Key columns are always included. |
| `flatten` / `arraySeparator` | `address.city` columns and joined arrays (default on, `, `). When off, nested values are stored as JSON text. |
| `valueInputOption` | `RAW` (default, safe) or `USER_ENTERED` (Google parses dates, numbers and formulas). |
| `maxRows` | Process at most this many rows. |
| `maxRowsPerTab` | Rollover: start `<Tab> (2)` when a tab has this many data rows. |
| `batchSize` | Rows per write request (default 1000). |
| `dryRun` | Report what would change and write nothing. Without a key, it only checks the data and the columns. |

```json
{
  "spreadsheetId": "https://docs.google.com/spreadsheets/d/1AbC.../edit#gid=0",
  "serviceAccountKey": "{ \"type\": \"service_account\", ... }",
  "sheetName": "Products",
  "mode": "upsert",
  "keyColumns": ["url"],
  "datasetId": "aBcDeF123456"
}
```

### Output

Each run stores a summary in the key-value store under `OUTPUT` and also pushes it to the default dataset as one record. In `read` mode the dataset holds the sheet rows instead.

```json
{
  "mode": "upsert", "dryRun": false, "sheetName": "Products",
  "rowsInput": 1250, "rowsAppended": 140, "rowsUpdated": 85, "rowsSkipped": 1025,
  "skipped": {"duplicate": 3, "unchanged": 1022, "missingKey": 0, "empty": 0},
  "rowsNotWritten": 0, "columnsAdded": 1, "newColumns": ["discountPrice"],
  "tabsUsed": ["Products"], "tabsCreated": [], "spreadsheetFull": false, "chargeLimitReached": false,
  "spreadsheetUrl": "https://docs.google.com/spreadsheets/d/1AbC.../edit",
  "cellsUsed": 48210, "cellLimit": 10000000, "warnings": [], "error": null
}
```

If the run fails, for example because the sheet isn't shared, the summary still lists how many rows were written before the error, and `error` holds the plain-English reason.

### Pricing

Pay per event:

- **USD 0.0001 per row written**, i.e. USD 0.10 per 1,000 rows appended or updated.
- A start fee of USD 0.005 per run.
- Skipped, unchanged and duplicate rows are free, and so are dry runs (start fee only).

You can set a maximum cost per run in Apify Console. When the Actor reaches it, it stops writing cleanly, and the summary reports `chargeLimitReached`.

### Run it from code or an AI agent

Everything the Console does is one API call away. Get your token under **Settings > API & Integrations**.

**Python** (`pip install apify-client`)

```python
from apify_client import ApifyClient

client = ApifyClient("<APIFY_TOKEN>")
run = client.actor("panthalus/google-sheets-sync").call(run_input={
    "spreadsheetId": "https://docs.google.com/spreadsheets/d/<ID>/edit",
    "serviceAccountKey": open("service-account.json").read(),
    "mode": "upsert", "keyColumns": ["url"],
    "datasetId": "<DATASET_ID>",
})
print(client.key_value_store(run["defaultKeyValueStoreId"]).get_record("OUTPUT")["value"])
```

**JavaScript** (`npm i apify-client`)

```js
import { ApifyClient } from 'apify-client';
import { readFileSync } from 'node:fs';

const client = new ApifyClient({ token: '<APIFY_TOKEN>' });
const run = await client.actor('panthalus/google-sheets-sync').call({
    spreadsheetId: 'https://docs.google.com/spreadsheets/d/<ID>/edit',
    serviceAccountKey: readFileSync('service-account.json', 'utf8'),
    mode: 'append', dedupe: true,
    items: [{ name: 'Alpha', price: 9.5 }, { name: 'Beta', price: 12 }],
});
const { value } = await client.keyValueStore(run.defaultKeyValueStoreId).getRecord('OUTPUT');
console.log(value);
```

**cURL** (runs the Actor and returns the summary in one request)

```bash
curl -X POST "https://api.apify.com/v2/acts/panthalus~google-sheets-sync/run-sync-get-dataset-items?token=<APIFY_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{"spreadsheetId": "<ID>", "serviceAccountKey": "<KEY JSON AS STRING>", "mode": "append", "jsonUrl": "https://example.com/data.json"}'
```

**AI agents (MCP).** Add this Actor as a tool in Claude, Cursor, VS Code or any MCP client:

```
https://mcp.apify.com?tools=panthalus/google-sheets-sync
```

Then you can just ask, for example: *"Put these 40 leads into the 'Leads' tab of my sheet, and update any that are already there by email."* The Actor uses pay-per-event pricing with limited permissions, so it is eligible for Apify's agentic payments.

**Schedules.** Run a scraper on an Apify Schedule and add this Actor as its integration. Your sheet then updates by itself.

### FAQ

**Is my data private? Do you store my key?** No. Your data goes straight from your Apify dataset (or your JSON) to your Google Sheet, inside your own Apify run. We never store or see your data or your key. The key is an encrypted secret input: it's used only to get a short-lived Google access token, and it never appears in logs, outputs or error messages. The only thing the run saves is the summary, in your own run storage.

**Why a service account and not "Sign in with Google"?** A service account can only open the spreadsheets you explicitly share with it. It can't see the rest of your Drive, it doesn't expire like a login session, and you can revoke it any time by un-sharing the sheet or deleting the key.

**"Your organization doesn't allow key creation".** Some Google Workspace organizations block service-account keys through the policy `iam.disableServiceAccountKeyCreation`. Ask your admin to allow it for one project, or create the project under a personal Google account and share the sheet with that service account.

**How fast is it?** Google allows about 60 write requests per minute per service account, and each request carries up to 1,000 rows. Large exports move at tens of thousands of rows per minute. Upsert and dedupe first read the existing tab, which adds a few seconds per 10,000 rows.

**What counts toward the 10M-cell limit?** Every cell of every tab, including empty grid cells (a new tab already has 26,000 of them). The run summary shows `cellsUsed`. To free space, delete unused tabs or empty rows and columns, or use `replace`, which shrinks the tab to fit the data.

**A run failed halfway. Will re-running create duplicates?** Rows written before the error are listed in the summary. Re-run with `upsert` (with key columns) or `dedupe` on, and only the missing rows will be added.

**My tab has blank rows in the middle.** In plain append mode Google adds new rows after the first block of data, inserting them so that nothing is overwritten. If you want them strictly after the very last row, turn on `dedupe` or use `upsert`: the Actor then reads the tab and writes to exact row numbers.

**Does replace delete anything else?** It clears the chosen tab and deletes its rollover tabs (`<Tab> (2)`, `<Tab> (3)`...). Other tabs are never touched.

**Can it read a sheet?** Yes: `mode: "read"` turns a tab into dataset items, with the header row as field names. Blank headers become `column_C` and repeated names become `name_2`.

**Can I use an Excel file?** Only after converting it: open it in Google Drive and choose **File > Save as Google Sheets**, then use the new spreadsheet's URL.

Developer: Panthalus.

# Actor input Schema

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

Paste the spreadsheet URL from your browser (https://docs.google.com/spreadsheets/d/.../edit) or just the long ID between /d/ and /edit. If the URL ends in #gid=..., that tab is used when "Tab name" is empty. The prefilled link is Google's read-only sample sheet: with no key it gives a free demo dry run.

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

Paste the whole content of your Google service-account .json key file. Stored encrypted by Apify, never logged or returned. Share the spreadsheet with the service account's email (client_email in the key) as Editor. Setup steps are in the README.

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

Tab (sheet) to write to or read from. Created if it doesn't exist. Empty = the tab in the URL's #gid, else the first tab.

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

append: add rows below existing data. replace: clear the tab and write the new data (the tab is left untouched if there is no data). upsert: update rows whose key columns match, append the rest. read: copy the tab into this run's dataset.

## `keyColumns` (type: `array`):

Column(s) that identify a row, e.g. url, or sku + store. Required for upsert; with dedupe in append mode, rows whose key is already in the sheet are skipped. Nested fields use dot notation (address.city).

## `dedupe` (type: `boolean`):

Skip rows already in the sheet and repeated rows within this run. Without key columns, a row is a duplicate when all its values match an existing row; with key columns, when its key matches.

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

Apify dataset to export (ID or username~name). When this Actor is added as an integration, the triggering run's dataset is used automatically.

## `items` (type: `array`):

Rows as a JSON array of objects, e.g. \[{"name": "A", "price": 1}]. Handy for API and AI-agent calls.

## `jsonUrl` (type: `string`):

URL that returns a JSON array, an object with an items/data/results array, or JSON Lines. Max 200 MB.

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

Only these fields, in this order. Empty = all fields. Key columns are always included.

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

Nested objects become dot.notation columns (address.city) and arrays of plain values are joined into one cell. Arrays of objects are stored as compact JSON. Off = nested values stored as JSON text.

## `arraySeparator` (type: `string`):

Text placed between array values when flattening, e.g. ", " or " | ".

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

RAW (recommended): text is stored exactly as given, so scraped text starting with = is never run as a formula. USER_ENTERED: Google parses values like a person typing (dates, currencies, formulas).

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

Process at most this many input rows (write modes) or sheet rows (read mode). Empty = all.

## `maxRowsPerTab` (type: `integer`):

When a tab holds this many data rows, continue in a new tab named "<Tab name> (2)", "(3)"... Upsert and dedupe look across all of them. Empty = no limit.

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

Rows sent to Google per write request (also capped at about 2 MB). Lower it if your rows are very wide.

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

Validate everything and report what would change (rows to append/update/skip, new columns, tabs, a preview) without writing anything. Only the start fee is charged. Works even without a key (checks the data only).

## Actor input object example

```json
{
  "spreadsheetId": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit",
  "mode": "append",
  "dedupe": false,
  "flatten": true,
  "arraySeparator": ", ",
  "valueInputOption": "RAW",
  "batchSize": 1000,
  "dryRun": false
}
```

# Actor output Schema

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

Rows appended, updated and skipped, columns added, tabs used, spreadsheet URL, warnings and any error.

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

Write modes: one summary record. Read mode: one item per sheet row (header row = field names).

# 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 = {
    "spreadsheetId": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit"
};

// Run the Actor and wait for it to finish
const run = await client.actor("panthalus/google-sheets-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 = { "spreadsheetId": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit" }

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

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,panthalus/google-sheets-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/SB3zNOV0kShdMUkr4/builds/E6M8e4uYjubJlsl8s/openapi.json
