# Google Sheets Import & Export: Sync Apify Datasets (`registrydata/google-sheets-import-export`) Actor

Export an Apify dataset to a Google Sheet (append, replace or add only new rows) or import a sheet into a dataset. Uses your own service account, no OAuth login.

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

## Pricing

from $0.30 / 1,000 row exporteds

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: Sync Apify Datasets

Send the results of any Apify Actor run to a Google Sheet, or read a Google Sheet into an Apify dataset. Export with three safe modes (append, replace, or add only the rows that are not in the sheet yet), keep your own column order, and run it on a schedule. It authenticates with **your own Google service account**, so there is no OAuth pop-up, no shared access to your Google account, and nothing to re-authorize.

**Price: $0.30 per 1,000 rows exported.** Rows imported: $0.30 per 1,000. Set a maximum cost per run and the run stops there. Details under [Pricing](#pricing).

Without a spreadsheet or key it runs a harmless preview on sample data, so you can see exactly what would be written.

### What it does

| Direction | What happens |
|---|---|
| **Export** | Reads an Apify dataset and writes it to a tab of your spreadsheet: a header row (column names) followed by one row per record. |
| **Import** | Reads a tab (or a cell range) of your spreadsheet and saves each row as a record in this run's dataset, using the header row as field names. |

Export write modes:

- **Append rows:** adds the records below the existing rows. New fields in your data get new columns on the right; existing columns keep their place.
- **Replace the whole tab:** clears the tab, then writes the header and all records.
- **Append only new rows:** skips records whose key fields (for example `url` or `id`) are already in the sheet, and skips repeats inside the dataset. Run it daily from a schedule and the sheet fills without duplicates.

### Set-up (about 5 minutes, once)

1. In Google Cloud, create a project, enable the **Google Sheets API**, create a **service account**, and download its **JSON key**.
2. Open your spreadsheet, click Share, and add the service account's `client_email` (it looks like `name@project.iam.gserviceaccount.com`) as **Editor** (Viewer is enough for import).
3. Paste the JSON key into **Service account key**, the spreadsheet URL into **Spreadsheet URL or ID**, and choose the dataset to export.

The key field is stored as an encrypted secret by Apify and is never written to logs or output. Use a service account created only for this purpose, and share only the spreadsheets you want it to touch.

### Input

```json
{
  "mode": "export",
  "spreadsheet": "https://docs.google.com/spreadsheets/d/<your spreadsheet id>/edit",
  "sheetName": "Leads",
  "serviceAccountKey": { "...": "contents of the downloaded JSON key" },
  "dataset": "<dataset picked from your account>",
  "writeMode": "append_new_only",
  "keyFields": ["url"],
  "fields": ["name", "url", "price", "address.city"],
  "maxRows": 0
}
```

| Field | Meaning |
|---|---|
| `mode` | `export` (dataset to sheet, default) or `import` (sheet to dataset) |
| `spreadsheet` | Spreadsheet URL or ID. Empty runs the sample preview |
| `sheetName` | Tab name (default `Sheet1`). Export creates a missing tab; import needs it to exist |
| `serviceAccountKey` | The service account JSON key (secret) |
| `dataset` | Export only: the dataset to write, chosen in the picker |
| `writeMode` | `append`, `replace` or `append_new_only` |
| `keyFields` | Fields that identify a record, for `append_new_only` |
| `fields` | Optional columns to write, in order; dotted names reach nested values. Empty writes every top-level field |
| `importRange` | Import only: optional A1 range such as `A1:F500` (first row = column names) |
| `maxRows` | Stop after this many records or rows (0 = no limit) |
| `dryRun` | Show the header and first rows that would be written; contacts nothing, charges nothing |

### How values are written

- Numbers and true/false stay numbers and true/false. Empty values become empty cells.
- Objects and lists (for example `tags` or `address`) are written as compact JSON text in one cell; use `fields` with a dotted name such as `address.city` to get a nested value into its own column.
- Text is written exactly as it is (Google's "raw" input mode): a value that starts with `=` is stored as text and never runs as a formula, so scraped data cannot execute anything in your sheet.
- Text longer than Google's limit of 50,000 characters per cell is cut, and the run summary counts how many cells were cut.

### Output

Export writes the sheet and saves a `SUMMARY` record in the run's key-value store (rows written, rows skipped, columns, columns added). Import saves one dataset item per sheet row: numbers stay numbers, blank cells are left out, repeated or blank header names get safe names (`name_2`, `C`). The preview (no credentials, or `dryRun`) saves a `PREVIEW` record.

Example `SUMMARY` after an export:

```json
{
  "rows_written": 120,
  "rows_skipped_existing": 30,
  "rows_skipped_duplicate_in_dataset": 0,
  "cells_truncated_to_50000_characters": 0,
  "columns": ["name", "url", "price", "address.city"],
  "columns_added": [],
  "stopped_at_spending_limit": false,
  "sheet": "Leads"
}
```

### Pricing

Pay per use: **$0.30 per 1,000 rows** exported, or per 1,000 rows imported (imported rows are saved as dataset items), plus Apify's per-run start fee. The preview writes nothing and charges nothing for rows. Records skipped as duplicates, and rows that could not be written, are not billed.

Example: exporting 12,000 records costs $3.60. Appending 50 new rows to a sheet every day costs $0.015 a day plus the run start fee. Use `maxRows` to cap any run.

### Limits and honest notes

- **Google limits apply:** 10,000,000 cells per spreadsheet and 50,000 characters per cell. The Actor checks the cell limit before writing and refuses an export that would exceed it, leaving the sheet untouched.
- **Quotas:** Google allows about 60 write requests per minute per service account. The Actor sends one request per 5,000 rows (fewer for wide data) at no more than one per 1.1 seconds, and waits and retries when Google asks it to.
- **Replace is not atomic:** it clears the tab and then writes. If the run is interrupted midway, the tab holds a partial copy. Use Append or "Append only new rows" for data you cannot afford to lose.
- **Memory:** an export reads the dataset into memory before writing. We measured about 150 MB per million cells (200,000 rows of 10 columns peaked at about 310 MB), so the 10-million-cell maximum needs about 2 GB; set the run memory accordingly.
- **Header row required:** to append to an existing tab, row 1 must hold the column names. A sheet that is empty gets a header written automatically.
- **Formatting is not touched:** the Actor writes values only. Formats, filters and formulas elsewhere in the sheet stay as they are.
- **One tab per run.** Run it again for another tab.

### FAQ

**Is it safe to give a service account access to my spreadsheet?** The service account can read and edit only the spreadsheets you share with its `client_email`, nothing else in your Google account. Remove it from the sheet's sharing list at any time to revoke access.

**Why a service account instead of "sign in with Google"?** It needs no consent screen, never expires on a schedule, and cannot touch anything you did not explicitly share.

**Can I schedule it?** Yes. Use an Apify Schedule or an integration that starts this Actor when another Actor finishes. For automatic exports, pick `append_new_only` with a key field.

**Can I call it from the API or an AI agent?** Yes, like any Apify Actor: start it with the Apify API, client libraries or MCP.

**What happens when I hit my spending limit?** The export stops before writing rows you cannot be billed for, and the status message says how many were written.

**Why did I get "Google denied access"?** The spreadsheet is not shared with the service account's `client_email`, or the Google Sheets API is not enabled in the key's Google Cloud project.

# Actor input Schema

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

Export writes an Apify dataset into the sheet. Import reads the sheet into this run's dataset.

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

The Google Sheets URL, or the long ID inside it. Share the spreadsheet with the service account's <code>client_email</code> first (Editor to export, Viewer is enough to import). Leave empty to run the sample preview.

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

Name of the tab to write or read. When exporting, a missing tab is created.

## `serviceAccountKey` (type: `object`):

The JSON key file of a Google Cloud service account that has the Google Sheets API enabled. It is stored as a secret, encrypted by Apify, and never printed. See the README for the three setup steps.

## `dataset` (type: `string`):

Export only. The Apify dataset whose items are written to the sheet.

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

Append adds rows below the existing ones. Replace clears the tab first. Add only new rows skips records whose key fields already appear in the sheet, so you can run it on a schedule without duplicates.

## `keyFields` (type: `array`):

Fields that identify a record, for example <code>url</code> or <code>id</code>. Used by "Append only new rows".

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

Optional. The fields to write, in column order. Dotted names reach nested values (<code>address.city</code>). Empty exports every top-level field.

## `importRange` (type: `string`):

Import only. Optional A1 range such as <code>A1:F500</code>. The first row of the range must hold the column names. Empty reads the whole tab.

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

Stop after this many dataset items (export) or sheet rows (import). 0 means no limit. Use it to cap the cost of a run.

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

Show the header and first rows that would be written, without contacting Google and without any charge.

## Actor input object example

```json
{
  "mode": "export",
  "sheetName": "Sheet1",
  "writeMode": "append",
  "keyFields": [],
  "fields": [],
  "maxRows": 0,
  "dryRun": false
}
```

# Actor output Schema

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

No description

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

No description

## `preview` (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("registrydata/google-sheets-import-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("registrydata/google-sheets-import-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 registrydata/google-sheets-import-export --silent --output-dataset

```

## MCP server setup

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