# Google Sheets Export & Import (Reliable, No OAuth) (`sharkinho/google-sheets-sync`) Actor

Send any Apify dataset, run or JSON to Google Sheets, or read a sheet back into a dataset. Service-account auth that never expires, automatic retries on Google rate limits, append / replace / de-duplicate modes.

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

## Pricing

$0.10 / 1,000 row written or reads

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 & Import: reliable, no OAuth

Send the results of **any Apify Actor** (or any JSON) to **Google Sheets**, or read a sheet back into a dataset.

Built to work on every run:

- **Authentication never expires.** It uses a Google *service account*, not an OAuth login that breaks after a few days.
- **Rate limits are retried automatically.** Google `429` / `5xx` errors get exponential backoff, so big exports finish.
- **Large exports are batched.** Rows are written in chunks of 5,000, and the tab gets more columns when needed.
- **Data is written exactly as is.** By default nothing is interpreted as a formula, so scraped text like `=IMPORTXML(...)` can't run in your sheet.
- **Three write modes:** `append`, `replace`, and `append-unique`, which only adds rows whose key (`url`, `id`…) is not in the sheet yet. That makes it a good fit for scheduled scrapers.
- **Nested JSON is flattened** to columns (`seller.name`, `price.value`). Lists become comma-separated text.
- **Columns stay stable.** In append mode new fields are added to the right, and existing columns never move.

### Try it in 10 seconds

Click **Start** with the default input. Without a key, the Actor writes the sample data to our demo spreadsheet and shows the result, so you can see how it works before setting anything up.

### Setup (2 minutes, once)

1. Go to [Google Cloud Console → Service accounts](https://console.cloud.google.com/iam-admin/serviceaccounts). Create a project if asked, then **Create service account**. A name is enough; no roles are needed.
2. Open the service account, then go to **Keys → Add key → Create new key → JSON**. A `.json` file downloads.
3. Enable the **[Google Sheets API](https://console.cloud.google.com/apis/library/sheets.googleapis.com)** for the same project.
4. In your spreadsheet, click **Share** and add the service account's email (`...@...iam.gserviceaccount.com`) as **Editor**.
5. Paste the whole content of the `.json` file into **Service account JSON key**. Apify stores it encrypted.

That's it. The same key works for every spreadsheet you share with that email.

### Typical uses

#### Export every scraper run automatically

Open your scraper (Google Maps, Instagram, Amazon…) and go to **Integrations → Add integration → Actor**. Pick this Actor, set the spreadsheet and set **Dataset** to `{{resource.defaultDatasetId}}`. After each successful run, the run's dataset is pushed to the sheet. Use `append-unique` with `uniqueKey: url` to collect only new items.

#### Export an existing dataset

```json
{
  "spreadsheet": "https://docs.google.com/spreadsheets/d/1AbC.../edit",
  "sheetName": "Leads",
  "datasetId": "aBcD1234",
  "mode": "replace",
  "serviceAccountKey": "{ ...json key... }"
}
```

#### Read a sheet into a dataset

Use `"operation": "read"`. The first row is the header, and every following row becomes a JSON object you can feed to other Actors, such as a list of URLs to scrape.

### Input

| Field | Description |
|---|---|
| `spreadsheet` | Spreadsheet URL or ID |
| `sheetName` | Tab name. Created automatically if missing. |
| `serviceAccountKey` | JSON key (secret) |
| `operation` | `write` (default) or `read` |
| `mode` | `append` (default), `replace`, `append-unique` |
| `uniqueKey` | Key column for `append-unique` |
| `datasetId` / `jsonUrl` / `data` | Data source. In integrations, set `datasetId` to `{{resource.defaultDatasetId}}`. |
| `fields` / `omitFields` | Choose and order the columns |
| `flatten` | Flatten nested objects (default `true`) |
| `parseValues` | Let Sheets parse formulas and dates (default `false`) |
| `maxItems` | Row limit |

### Output

A summary item with the spreadsheet link, the tab, the number of rows written and the number of columns. In read mode, the dataset contains the sheet rows.

### Pricing

You pay only for rows actually written or read. See the pricing tab; it's cents per thousand rows. The run stops cleanly at your *max cost per run*.

### Limits and tips

- Google Sheets allows up to 10 million cells per spreadsheet and 50,000 characters per cell. Longer values are truncated and marked `…[truncated]`.
- For millions of rows, use a database or BigQuery. Sheets slows down with huge tabs.
- **Error "Cannot access the spreadsheet"** means you need to share the sheet with the service account email as Editor.
- **Error "Google Sheets API is not enabled"** means you need to enable it (step 3) and wait a minute.

Found a bug or need a feature? Open an issue in the **Issues** tab. Fixes usually ship within 24 hours.

### FAQ

**Why a service account instead of "Sign in with Google"?**
OAuth logins used by other export tools expire or get revoked, and scheduled exports silently stop. A service account key keeps working until you delete it, which makes it a better fit for daily or hourly integrations.

**Can I export the results of someone else's Actor?**
Yes. Any dataset you can access works. Add this Actor as an integration on that Actor and set **Dataset** to `{{resource.defaultDatasetId}}`.

**How do I avoid duplicate rows when a scraper runs every day?**
Use the `append-unique` mode with `uniqueKey` set to a stable field such as `url` or `id`. Rows whose key is already in the sheet are skipped and not charged.

**Will my formulas break when new fields appear?**
No. In append mode new fields are added as new columns on the right. Existing columns never move.

**Is my key safe?**
The key field is marked secret, so Apify stores it encrypted and never shows it in logs. Give the service account access only to the spreadsheets you share with it. It cannot see the rest of your Google Drive.

**What does it cost?**
$0.0001 per row written or read, which is $1 per 10,000 rows. A demo run without a key writes 2 sample rows, so it costs $0.0002.

# Actor input Schema

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

The Google Sheets URL (or just its ID). Share the spreadsheet with your service account email as Editor. Leave empty together with the key to try the public demo.

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

Tab to write to / read from. Created automatically if it does not exist. Default: first tab.

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

Full JSON key of a Google service account (stored encrypted). See the README for the 2-minute setup. Leave empty to run the demo.

## `operation` (type: `string`):

write: send data to the sheet. read: load the sheet into this run's dataset.

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

append: add rows below existing data (new columns are added to the right). replace: clear the tab first. append-unique: append only rows whose unique key is not already in the sheet.

## `uniqueKey` (type: `string`):

Field that identifies a row, e.g. url or id. Required for append-unique.

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

Apify dataset to export. Pick one of your datasets or paste its ID. To export every run of another Actor automatically, add this Actor as an integration and set this field to {{resource.defaultDatasetId}}.

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

URL returning a JSON array (or an object with items/data array).

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

Array of objects to write.

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

A1 range to read, e.g. A1:F500. First row must be the header. Default: whole tab.

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

Only these fields, in this order. Use dot notation for nested fields (seller.name). Empty = all fields.

## `omitFields` (type: `array`):

Fields to leave out of the sheet, e.g. html or images. Use dot notation for nested fields (seller.id).

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

Turn {seller: {name}} into a column seller.name. Arrays of plain values are joined with commas.

## `parseValues` (type: `boolean`):

Off (default) writes values exactly as they are, which protects against formula injection from scraped text. On = values are parsed as if typed by a user.

## `maxItems` (type: `integer`):

Limit the number of rows written or read. 0 = no limit.

## Actor input object example

```json
{
  "operation": "write",
  "mode": "append",
  "data": [
    {
      "product": "Coffee beans 1kg",
      "price": 18.9,
      "inStock": true,
      "tags": [
        "coffee",
        "beans"
      ],
      "seller": {
        "name": "Roastery A",
        "country": "PT"
      }
    },
    {
      "product": "Espresso cups (6)",
      "price": 24.5,
      "inStock": false,
      "tags": [
        "kitchen"
      ],
      "seller": {
        "name": "Shop B",
        "country": "ES"
      }
    }
  ],
  "flatten": true,
  "parseValues": false,
  "maxItems": 0
}
```

# Actor output Schema

## `overview` (type: `string`):

No description

## `rows` (type: `string`):

No description

## `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 = {
    "data": [
        {
            "product": "Coffee beans 1kg",
            "price": 18.9,
            "inStock": true,
            "tags": [
                "coffee",
                "beans"
            ],
            "seller": {
                "name": "Roastery A",
                "country": "PT"
            }
        },
        {
            "product": "Espresso cups (6)",
            "price": 24.5,
            "inStock": false,
            "tags": [
                "kitchen"
            ],
            "seller": {
                "name": "Shop B",
                "country": "ES"
            }
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("sharkinho/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 = { "data": [
        {
            "product": "Coffee beans 1kg",
            "price": 18.9,
            "inStock": True,
            "tags": [
                "coffee",
                "beans",
            ],
            "seller": {
                "name": "Roastery A",
                "country": "PT",
            },
        },
        {
            "product": "Espresso cups (6)",
            "price": 24.5,
            "inStock": False,
            "tags": ["kitchen"],
            "seller": {
                "name": "Shop B",
                "country": "ES",
            },
        },
    ] }

# Run the Actor and wait for it to finish
run = client.actor("sharkinho/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 '{
  "data": [
    {
      "product": "Coffee beans 1kg",
      "price": 18.9,
      "inStock": true,
      "tags": [
        "coffee",
        "beans"
      ],
      "seller": {
        "name": "Roastery A",
        "country": "PT"
      }
    },
    {
      "product": "Espresso cups (6)",
      "price": 24.5,
      "inStock": false,
      "tags": [
        "kitchen"
      ],
      "seller": {
        "name": "Shop B",
        "country": "ES"
      }
    }
  ]
}' |
apify call sharkinho/google-sheets-sync --silent --output-dataset

```

## MCP server setup

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