# Google Sheets Import & Export (append, upsert, dedupe) (`solidactors/google-sheets-import-export`) Actor

Export any Apify dataset to Google Sheets or read a sheet into a dataset. Append without overwriting, upsert by key, skip or remove duplicates, clear error messages and retries on Google limits. Uses your own service account.

- **URL**: https://apify.com/solidactors/google-sheets-import-export.md
- **Developed by:** [Solid Actors](https://apify.com/solidactors) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 83.3% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.05 / 1,000 row processeds

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 (append, upsert, dedupe)

Send any Apify dataset to a Google Sheet, or read a Google Sheet into a dataset. Built to be boring and reliable: append really appends, upsert updates by key, duplicates are skipped or removed, and when something is wrong you get a sentence that tells you what to fix.

### What it does

| Mode | What happens |
|---|---|
| `append` | Adds the new rows under the last row of the tab. Never overwrites. New columns are added to the header on the right. Optional: skip rows whose key is already in the sheet. |
| `replace` | Replaces the content of the tab with the new data. The new data is written first and the old leftovers are cleared after, so the tab is never empty if a run stops midway. |
| `upsert` | Rows whose key (for example `url` or `id`) already exist are updated in place; the rest are added. Columns you do not send are kept. |
| `dedupe` | Removes duplicate rows already in the sheet, by key columns or by the whole row. |
| `read` | Copies the tab into the dataset of the run (first row = field names). Public sheets work without any credentials. |

Typical use: run it after a scraper (Integrations, "Run Actor" after success) with `datasetId` = `{{resource.defaultDatasetId}}`, so every scrape lands in the same sheet without duplicates.

### Why this one

- **Append is a real append.** Rows are written to an exact row range after the last used row, not through Google's "table detection", which is what makes other tools overwrite or misplace data when a sheet has gaps.
- **Plain-language errors.** "Share the sheet with `my-bot@project.iam.gserviceaccount.com` as Editor", "Turn on the Google Sheets API here: (link)", "The tab names in this spreadsheet are: ...". No stack traces.
- **Retries.** Google rate limits (HTTP 429) and server errors are retried with backoff, up to 7 times per request.
- **Cell limit guard.** Google allows 10 million cells per spreadsheet and counts empty cells too. The Actor shrinks the tab to the data after writing and stops before a write that would go over the limit, instead of failing halfway.
- **Safe values by default.** Text that starts with `=` stays text (no formula injection from scraped data). Turn on `parseValues` if you want Google to parse formulas and dates.
- **Nested data flattened** like the Apify CSV export (`address/city`, `tags/0`), or kept as JSON text.
- **Dry run** checks access, keys and size without writing.
- **Your own credentials.** Nothing to authorize with a third party: you use a Google service account you control (or your own OAuth client).

### Set up Google access (5 minutes, free, once)

1. Open https://console.cloud.google.com/ and create a project (or use one you have).
2. Turn on the Google Sheets API: https://console.cloud.google.com/apis/library/sheets.googleapis.com, click **Enable**.
3. Go to **IAM and admin, Service accounts, Create service account**. Any name. Skip the optional steps.
4. Open the new service account, tab **Keys, Add key, Create new key, JSON**. A `.json` file downloads.
5. Paste the whole content of that file into the input field **Service account key (JSON)**. Apify stores it encrypted.
6. Open your spreadsheet, click **Share**, add the service account e-mail (it ends in `iam.gserviceaccount.com`) as **Editor**. Untick "Notify people".

Reading a sheet that is shared as "Anyone with the link can view" needs no credentials at all.

Prefer OAuth? Fill `oauthClientId`, `oauthClientSecret` and `oauthRefreshToken` from your own Google Cloud OAuth client (scope `https://www.googleapis.com/auth/spreadsheets`).

### Input example

```json
{
  "mode": "upsert",
  "spreadsheetId": "https://docs.google.com/spreadsheets/d/1AbC.../edit",
  "sheetName": "Leads",
  "datasetId": "{{resource.defaultDatasetId}}",
  "keyColumns": ["url"],
  "columnsOrder": ["url", "name", "email"],
  "serviceAccountJson": "{ \"type\": \"service_account\", ... }"
}
```

Other modes: `"mode": "append"` with `"skipDuplicates": true`, `"mode": "replace"`, `"mode": "dedupe"` with `"keyColumns": ["email"]`, `"mode": "read"`.

### Output example

Write modes push one summary row to the dataset (also saved as `SUMMARY` in the key-value store):

```json
{
  "status": "ok",
  "mode": "upsert",
  "spreadsheetUrl": "https://docs.google.com/spreadsheets/d/1AbC.../edit",
  "sheetName": "Leads",
  "rowsInput": 5000,
  "rowsWritten": 1200,
  "rowsUpdated": 3800,
  "rowsSkippedDuplicate": 0,
  "rowsRemovedDuplicate": 0,
  "newSheetCreated": false,
  "newColumnsAdded": ["phone"],
  "columns": 14,
  "cellsUsedAfter": 98014,
  "warnings": [],
  "error": null,
  "durationSec": 9.4
}
```

Read mode pushes one item per sheet row: `{"Student Name": "Alexandra", "Gender": "Female", "Home State": "CA", ...}`.

### Pricing

Pay per event: a small fee per run plus **$0.05 per 1,000 rows** written, updated or read (rows skipped as duplicates are not charged). Example: exporting a 5,000-row dataset costs about $0.25. Set a maximum cost per run in the run options if you want a hard cap; the Actor stops cleanly when it is reached.

### Limits

- Google limits: 10 million cells per spreadsheet, 50,000 characters per cell (longer values are cut and counted in `cellsTruncated`), and per-minute request quotas on your Google project (handled by retries).
- `upsert`, `dedupe` and `append` with `skipDuplicates` read the whole tab first. Very large tabs (millions of cells) need more memory: use 1 GB or more.
- A service account cannot create new spreadsheets in your Drive; create the spreadsheet yourself and share it. New tabs are created automatically.
- Reading a public sheet by tab name without credentials uses Google's CSV endpoint, which can blank cells in columns that mix numbers and text. Use credentials or the tab's `#gid=` URL for exact values.

### Questions and issues

Open an issue on the Actor page. Include the run ID; the summary already says what went wrong in most cases.

# Actor input Schema

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

append: add rows under the existing ones. replace: overwrite the tab with the new data. upsert: update rows whose key already exists, add the rest. dedupe: remove duplicate rows already in the sheet. read: copy the sheet into the dataset of this run.

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

Paste the full Google Sheets URL or just the ID (the long part between /d/ and /edit). If the URL has #gid=..., that tab is used.

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

Name of the tab. It is created if it does not exist (write modes). Empty means the first tab.

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

The Apify dataset whose items go to the sheet. In an integration after another Actor, use {{resource.defaultDatasetId}}.

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

An array of JSON objects to write, used instead of (or together with) the dataset. Each object becomes a row; keys become columns.

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

Column(s) that identify a row, for example url or id. Needed for upsert and for skip duplicates; optional for dedupe (empty means the whole row must match).

## `skipDuplicates` (type: `boolean`):

With mode append, rows whose key column(s) already exist in the sheet (or earlier in this run) are skipped instead of added again.

## `keyCaseInsensitive` (type: `boolean`):

Treat ABC and abc as the same key. Spaces at the start and end are always ignored.

## `columnsOrder` (type: `array`):

Columns to put first, in this order. Other columns follow in the order they appear in the data.

## `columnsToExclude` (type: `array`):

Column names (after flattening, for example address/city) that are not written.

## `flattenNested` (type: `boolean`):

On: an object address with a field city becomes a column address/city, like the Apify CSV export. Off: nested values are written as JSON text.

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

Off (safe default): values are written exactly as they are, text starting with = stays text. On: Google parses them as if typed by hand, so =SUM(...) becomes a formula and 2026-01-31 a date.

## `trimEmptyGrid` (type: `boolean`):

Google counts empty cells towards the 10 million cell limit. On: the tab is shrunk to the data after writing.

## `skipEmptyRows` (type: `boolean`):

In read mode, rows with no values are not pushed to the dataset.

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

Paste the whole .json key of a Google Cloud service account, then share the spreadsheet with that service account e-mail as Editor. Step by step in the README (5 minutes, free).

## `oauthClientId` (type: `string`):

Optional alternative to the service account: the OAuth client ID of your own Google Cloud app.

## `oauthClientSecret` (type: `string`):

The OAuth client secret of the same app.

## `oauthRefreshToken` (type: `string`):

A refresh token with the https://www.googleapis.com/auth/spreadsheets scope, made with your own OAuth client (for example in the Google OAuth Playground).

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

Rows sent to Google in one request (100 to 20,000). Requests are also cut at about 8 MB.

## `datasetOffset` (type: `integer`):

Start reading the dataset at this item.

## `datasetLimit` (type: `integer`):

Maximum rows taken from the dataset (write modes) or read from the sheet (read mode). Empty means all.

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

Checks access, the tab, the keys and the cell limit, and reports what would happen, without changing the sheet.

## Actor input object example

```json
{
  "mode": "read",
  "spreadsheetId": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit",
  "skipDuplicates": false,
  "keyCaseInsensitive": false,
  "flattenNested": true,
  "parseValues": false,
  "trimEmptyGrid": true,
  "skipEmptyRows": true,
  "batchSize": 5000,
  "datasetOffset": 0,
  "dryRun": false
}
```

# Actor output Schema

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

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

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

```

## MCP server setup

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