# Google Sheets Integration - Fast Import, Export & Upsert (`vnx0/google-sheets-integration`) Actor

Seamless bi-directional integration between Google Sheets and Apify. Export datasets to Google Sheets with smart flattening and key-based upserting; or import Google Sheets into Apify datasets with zero-auth public reading.

- **URL**: https://apify.com/vnx0/google-sheets-integration.md
- **Developed by:** [Vnx0](https://apify.com/vnx0) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$0.50 / 1,000 row synchronizeds

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 Integration - Fast Bi-Directional Sync & Key UPSERT

> The universal, bi-directional data bridge between Google Sheets and the Apify platform. Export any Apify scraper dataset into Google Sheets with smart nested JSON flattening, dynamic column reconciliation, and in-place key-based UPSERT—or turn any Google Sheet into an automated zero-auth input feed in under 1 second without complex coding or $25/mo Zapier subscriptions.

***

### ⚡ TL;DR & Quick Summary

- **Bi-Directional Pipeline**: Export Apify datasets to Google Sheets (`APPEND`, `OVERWRITE`, `UPSERT`) or import spreadsheet rows directly into typed Apify datasets.
- **Zero-Auth Public Reads**: Stream rows from any public Google Sheet link in under 1 second without a Google Cloud account, API key, or OAuth setup.
- **Key-Based UPSERT Engine**: Update existing rows by unique key (`id`, `sku`, `url`) in-place and append new rows—zero duplicate rows, zero broken formulas.
- **Smart Recursive JSON Flattener**: Automatically unfolds nested scraper JSON (`specs.dimensions.width`) into dot-notated columns—never see `[object Object]` again.
- **Enterprise Safety & Reliability**: Automatic 500-row batching, jittered exponential backoff for Google 60 req/min limits, 49,900-character cell truncation, and encrypted credentials (`isSecret: true`).
- **Transparent PPE Pricing**: Just **$0.0005 per row** ($0.50 per 1,000 rows). Platform compute is 100% covered by the creator; you only pay for actual rows delivered.

***

### 🎯 What Can You Do With This Integration?

Connect any web scraper or dataset to Google Sheets with zero friction:

- **🔄 Bi-Directional Flexibility**: Switch between exporting scraped data to sheets or reading live spreadsheet rows into your Apify actors with a single dropdown.
- **🔑 Key-Based UPSERT**: Match incoming records by primary key (`asin`, `sku`, `email`, `url`). Existing rows update cell values in-place (e.g. Row 42 updates price from $348 to $298), while newly discovered items append cleanly to the bottom.
- **🧩 Smart JSON Flattening**: Recursively unpacks deeply nested scraper objects into clean columns with custom delimiters (`specs.color`, `pricing.retail_usd`).
- **⚡ Dynamic Column Reconciliation**: When web scrapers discover new fields mid-crawl, new column headers are automatically created and aligned without corrupting existing rows.
- **🎨 Professional Styling**: Automatically freezes top header rows, applies bold styling, and sets auto-expanding column widths for presentation-ready sheets.
- **🛡️ Built-in Crash Protection**: Enforces Google's strict 50,000-character cell ceiling by safely truncating oversized content at 49,900 characters with `... [TRUNCATED]`.

***

### ⚡ How to Sync in 3 Easy Steps

1. **Open the Actor**: Sign up for a free Apify account (every account receives **$5.00 free credits monthly**).
2. **Choose Mode & Paste Target**: Select `IMPORT_FROM_SHEET` (Read) or `EXPORT_TO_SHEET` (Write), then paste your Google Sheet URL.
3. **Click "Save & Start"**: Watch records stream in real time. For exports, open your Google Sheet to see rows formatted with frozen headers.

```json
{
  "mode": "IMPORT_FROM_SHEET",
  "spreadsheet": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit",
  "sheetName": "Class Data",
  "publicSheet": true
}
```

***

### 🥊 Why This Actor Beats Alternatives

Legacy Google Sheets actors on Apify and third-party webhook tools suffer from frequent OAuth token expirations, 429 rate limit crashes, and mangled nested data:

| Capability | Legacy Apify Scrapers (`lukaskrivka`) | Zapier / Make.com | Raw Google Sheets API | **Google Sheets Integration (This Actor)** |
| :--- | :--- | :--- | :--- | :--- |
| **Pipeline Direction** | Clunky read, rigid export | Bi-directional (multi-step) | Raw code required | **Full Bi-Directional** (`EXPORT_TO_SHEET` & `IMPORT_FROM_SHEET`) |
| **Deduplication / Upsert** | ❌ None (Duplicates or full wipe) | Complex search + update steps | Manual row lookup logic | **✅ Native Key-Based UPSERT** (In-place cell update & net-new append) |
| **Public Sheet Access** | ❌ Requires Google Cloud credentials | ❌ Requires Google account login | ❌ Requires API key | **✅ Zero-Auth Instant Stream** (Reads public links in <1s) |
| **Header Drift Handling** | ❌ Scrambles columns in append mode | Rigid schema matching | Throws on mismatched ranges | **✅ Dynamic Reconciliation** (Auto-maps and expands new columns) |
| **Nested JSON Flattening** | ❌ Mangled as `[object Object]` | Requires JSON parse modules | Manual string serialization | **✅ Recursive Flattener** (`specs.color`, `pricing.retail`) |
| **Cell Overflow Protection** | ❌ Crashes with HTTP 400 on >50k chars | Truncates unpredictably | Fails whole batch | **✅ Safe Truncation** (Auto-caps at 49,900 chars with `... [TRUNCATED]`) |
| **Rate Limit Resilience** | ❌ Frequent Google 429 quota locks | Throttled / Slow execution | Requires custom retry logic | **✅ 500-Row Chunking + Jittered Exponential Backoff** |
| **Credential Security** | ❌ Stored in plaintext | Encrypted in third-party DB | Handled by developer | **✅ Encrypted at Rest** (`isSecret: true` in Apify Key-Value Store) |
| **Cost for 10,000 Rows** | High compute burn ($0.05 - $0.20+) | $25.00+ in task quotas | Free (with dev maintenance) | **$5.00 total** ($0.50/1k rows, compute 100% covered) |

***

### 💰 Transparent Pay-Per-Event (PPE) Pricing

This Actor uses Apify's **Pay-Per-Event (PPE)** pricing model. You pay only for actual rows processed:

| Rows Synchronized | Actor Cost (USD) | Effective Rate | Platform Compute Surcharge |
| :--- | :--- | :--- | :--- |
| **1,000 rows** | **$0.50** | $0.0005 per row | **$0.00 (Covered by Creator)** |
| **5,000 rows** | **$2.50** | $0.0005 per row | **$0.00 (Covered by Creator)** |
| **10,000 rows** | **$5.00** | $0.0005 per row | **$0.00 (Covered by Creator)** |
| **50,000 rows** | **$25.00** | $0.0005 per row | **$0.00 (Covered by Creator)** |
| **100,000 rows** | **$50.00** | $0.0005 per row | **$0.00 (Covered by Creator)** |

> 💡 **Apify Monthly Free Tier**: Every Apify account receives **$5.00 of free platform credits every month**, allowing you to synchronize up to **10,000 rows completely free** each month.

***

### 💼 High-Value Use Cases & Playbooks

#### 1. 🛒 E-Commerce & Retail: Live Competitor Price Tracker

- **The Problem**: Appending scraper runs to Google Sheets creates thousands of duplicate rows every day, breaking Looker Studio charts and formulas.
- **The Solution**: Set Write Mode to `UPSERT` with `upsertKey: "sku"`. As prices, stock status, or shipping costs fluctuate, the existing row updates in-place on row 42, while newly discovered items append cleanly to the bottom.

#### 2. 💼 B2B Lead Generation: Enriched Sales Pipelines

- **The Problem**: Sales teams need scraped leads from Google Maps, LinkedIn, or Apollo in their spreadsheet immediately, but scraping columns vary per lead.
- **The Solution**: Dynamic Header Reconciliation detects new fields (e.g. `instagram`, `direct_phone`, `employee_count`) and automatically expands the sheet headers to the right, mapping every lead to the exact column.

#### 3. 🤖 AI & RAG Engineers: Google Sheets as an Actor Input Queue

- **The Problem**: Non-technical team members need to manage URLs, keywords, or queries that scrapers consume without touching code or JSON inputs.
- **The Solution**: Team members add target URLs to a Google Sheet. Schedule this Actor to run daily in `IMPORT_FROM_SHEET` mode, streaming rows into the default dataset which downstream scraping actors read as their `startUrls`.

#### 4. 📈 SEO & Growth Marketers: Daily SERP Tracking

- **The Problem**: Need historical tracking of search engine result positions over months without manual copy-pasting.
- **The Solution**: Wire a Google Search Scraper to this Actor via webhook in `APPEND` mode. Daily keyword rankings, snippet text, and URLs are logged with timestamps into clean chronological rows.

***

### ⚡ Production Use-Case Recipes (Copy-Paste JSON)

#### Recipe 1: Instant Public Sheet Import (Zero Setup)

Stream data from any public Google Sheet into an Apify dataset with zero authentication:

```json
{
  "mode": "IMPORT_FROM_SHEET",
  "spreadsheet": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit",
  "sheetName": "Class Data",
  "publicSheet": true,
  "inferTypes": true
}
```

#### Recipe 2: Export Apify Scraper Dataset (Append Mode)

Append new records from any scraper run to an existing Google Sheet:

```json
{
  "mode": "EXPORT_TO_SHEET",
  "spreadsheet": "https://docs.google.com/spreadsheets/d/YOUR_SPREADSHEET_ID/edit",
  "sheetName": "Scraped Leads",
  "datasetId": "YOUR_DATASET_ID",
  "writeMode": "APPEND",
  "flattenNestedObjects": true,
  "formatSheet": true,
  "serviceAccountEmail": "my-service-account@project.iam.gserviceaccount.com",
  "serviceAccountPrivateKey": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASC..."
}
```

#### Recipe 3: Key-Based UPSERT for Price Tracking

Update matching products by `sku` and append new items without creating duplicate rows:

```json
{
  "mode": "EXPORT_TO_SHEET",
  "spreadsheet": "https://docs.google.com/spreadsheets/d/YOUR_SPREADSHEET_ID/edit",
  "sheetName": "Live Catalog",
  "datasetId": "YOUR_DATASET_ID",
  "writeMode": "UPSERT",
  "upsertKey": "sku",
  "flattenNestedObjects": true,
  "serviceAccountEmail": "my-service-account@project.iam.gserviceaccount.com",
  "serviceAccountPrivateKey": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASC..."
}
```

#### Recipe 4: Overwrite Tab with Fresh Daily Snapshot

Completely refresh a spreadsheet tab with the latest dataset run using raw JSON credentials:

```json
{
  "mode": "EXPORT_TO_SHEET",
  "spreadsheet": "https://docs.google.com/spreadsheets/d/YOUR_SPREADSHEET_ID/edit",
  "sheetName": "Daily Snapshot",
  "writeMode": "OVERWRITE",
  "formatSheet": true,
  "serviceAccountJson": "{\"type\":\"service_account\",\"project_id\":\"my-project\",\"private_key\":\"...\",\"client_email\":\"...\"}"
}
```

***

### 🛠️ Setting Up Google Service Account (2-Minute Guide)

Writing to private Google Sheets or running automated `EXPORT` and `UPSERT` operations requires a Google Cloud Service Account. Unlike OAuth tokens, **service account keys never expire**, making them the industry standard for unattended cloud automations.

1. **Create Project & Enable API**:
   - Go to the [Google Cloud Console](https://console.cloud.google.com/).
   - Create a project (e.g. `Apify Sheets Integration`) and enable the **Google Sheets API**.
2. **Create Service Account**:
   - Navigate to **IAM & Admin** > **Service Accounts** and click **Create Service Account**.
   - Give it a name (e.g. `apify-sheets-sync`) and click **Done**.
3. **Generate Key**:
   - Click on your new service account, open the **Keys** tab, click **Add Key** > **Create new key**, and choose **JSON**.
   - Download the file to your computer.
4. **Share Your Spreadsheet**:
   - Open your target Google Sheet.
   - Click the green **Share** button in the top right.
   - Paste the service account email (e.g. `apify-sheets-sync@your-project.iam.gserviceaccount.com`) and grant **Editor** access.
5. **Paste into Actor**:
   - Paste the `client_email` and `private_key` into the Actor input (or paste the entire file into `serviceAccountJson`).

***

### 🔗 Automated Scraper Integration & Webhooks

You can configure any Apify web scraper (e.g. Google Maps Scraper, Amazon Scraper, Instagram Scraper) to automatically pipe its results into Google Sheets the second a run finishes.

#### Setup via Apify Console Webhook:

1. Open your scraping Actor in the [Apify Console](https://console.apify.com).
2. Navigate to the **Integrations** tab and click **Add Webhook**.
3. Select event trigger: **`Run succeeded`**.
4. Set Target URL to: `https://api.apify.com/v2/acts/vnx0~google-sheets-integration/runs?token=YOUR_APIFY_TOKEN`
5. Set Payload template:
   ```json
   {
     "mode": "EXPORT_TO_SHEET",
     "datasetId": "{{resource.defaultDatasetId}}",
     "spreadsheet": "https://docs.google.com/spreadsheets/d/YOUR_SPREADSHEET_ID/edit",
     "sheetName": "Scraped Records",
     "writeMode": "APPEND",
     "serviceAccountEmail": "@mySecretEmail",
     "serviceAccountPrivateKey": "@mySecretKey"
   }
   ```

#### Programmatic Invocation (Node.js & Python SDK):

**JavaScript / TypeScript (`apify-client`)**:

```javascript
import { ApifyClient } from 'apify-client';

const client = new ApifyClient({ token: 'YOUR_APIFY_TOKEN' });

const run = await client.actor('vnx0/google-sheets-integration').call({
    mode: 'EXPORT_TO_SHEET',
    spreadsheet: 'https://docs.google.com/spreadsheets/d/YOUR_SPREADSHEET_ID/edit',
    sheetName: 'Products',
    writeMode: 'UPSERT',
    upsertKey: 'sku',
    serviceAccountEmail: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
    serviceAccountPrivateKey: process.env.GOOGLE_SERVICE_ACCOUNT_KEY
});

console.log(`Export completed: ${run.id}`);
```

**Python (`apify-client`)**:

```python
from apify_client import ApifyClient
import os

client = ApifyClient("YOUR_APIFY_TOKEN")

run = client.actor("vnx0/google-sheets-integration").call(run_input={
    "mode": "IMPORT_FROM_SHEET",
    "spreadsheet": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit",
    "sheetName": "Class Data",
    "publicSheet": True
})

## Stream dataset items into your Python pipeline
dataset_items = client.dataset(run["defaultDatasetId"]).list_items().items
print(f"Imported {len(dataset_items)} rows")
```

***

### 📥 Input Parameters Dictionary

| Parameter | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `mode` | String | `"IMPORT_FROM_SHEET"` | Operation direction: `IMPORT_FROM_SHEET` (Read to dataset) or `EXPORT_TO_SHEET` (Write to sheet). |
| `spreadsheet` | String | *Pre-filled* | Full Google Sheets URL or bare Spreadsheet ID. |
| `sheetName` | String | `"Sheet1"` | Name of the sheet tab. Automatically created if missing during export. |
| `publicSheet` | Boolean | `true` | Set to `true` to stream public sheets ("Anyone with the link can view") without credentials. |
| `serviceAccountEmail` | String | `""` | Google Cloud Service Account email (required for private sheets and writes). |
| `serviceAccountPrivateKey` | String | `""` | Google Cloud Service Account private key string (encrypted at rest with `isSecret: true`). |
| `serviceAccountJson` | String | `""` | Alternative to fields above: paste entire service account JSON file (encrypted at rest with `isSecret: true`). |
| `datasetId` | String | `""` | Apify Dataset ID to export. If left blank, automatically uses the most recent actor run. |
| `writeMode` | String | `"APPEND"` | Write strategy: `APPEND` (add below), `OVERWRITE` (replace tab), or `UPSERT` (update by key). |
| `upsertKey` | String | `"id"` | Unique identifier column name used to match rows during `UPSERT` mode (e.g. `sku`, `url`). |
| `fields` | Array | `[]` | List of specific column names to export. Leave empty to automatically export all fields. |
| `flattenNestedObjects` | Boolean | `true` | Recursively flattens nested objects into dot-notated columns (`address.city`). |
| `flattenDelimiter` | String | `"."` | Delimiter character used to join nested object property keys. |
| `formatSheet` | Boolean | `true` | Freezes top header row, styles headers with bold text, and sets clean cell alignment. |
| `headerRowIndex` | Integer | `1` | Row number containing column headers for import (1-indexed). |
| `inferTypes` | Boolean | `true` | Automatically parses numeric strings, booleans, and ISO dates into typed JSON values. |
| `maxRows` | Integer | `10000` | Safety limit to prevent runaway memory or quota consumption. |
| `batchSize` | Integer | `500` | Batch chunk size per Google Sheets API request (optimized for throughput and rate limits). |

***

### 📤 Output Structure & Console Views

#### 1. Dual-Layer Dataset Records (Import Mode)

Imported rows emit dual-layer records: flat root attributes populate the Apify Console web table view immediately on Page 1, while complete raw payloads remain accessible under `_rawData` for downstream programmatic workflows:

```json
{
  "Student Name": "Alexandra",
  "Gender": "Female",
  "Class Level": "4. Senior",
  "Home State": "CA",
  "Major": "English",
  "Extracurricular Activity": "Drama Club",
  "_rowNumber": 2,
  "_sheetName": "Class Data",
  "_spreadsheetUrl": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit",
  "_spreadsheetId": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
  "_rawData": {
    "Student Name": "Alexandra",
    "Gender": "Female",
    "Class Level": "4. Senior",
    "Home State": "CA",
    "Major": "English",
    "Extracurricular Activity": "Drama Club"
  }
}
```

#### 2. Execution Telemetry Artifact (`OUTPUT`)

Every export or import run saves a detailed telemetry summary under the `OUTPUT` key in the default Key-Value Store:

```json
{
  "status": "SUCCESS",
  "mode": "EXPORT_TO_SHEET",
  "writeMode": "UPSERT",
  "spreadsheetId": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
  "spreadsheetUrl": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit",
  "sheetName": "Live Catalog",
  "rowsProcessed": 500,
  "rowsAppended": 420,
  "rowsUpdated": 80,
  "columnsCount": 16,
  "durationMs": 2450,
  "timestamp": "2026-11-17T01:30:00.000Z"
}
```

***

### 🛡️ Enterprise Reliability & Anti-Crash Architecture

- **Google API Rate Limit Resilience (60 req/min)**: Google limits writes to 60 requests per minute per user. This Actor batches operations into optimized 500-row chunks. A 10,000-row dataset writes in just 20 requests. If Google temporarily throttles requests with HTTP 429, the Actor automatically recovers using jittered exponential backoff.
- **Safe Cell Boundary Guard (49,900 Chars)**: Google Sheets strictly rejects any cell containing more than 50,000 characters with an `INVALID_ARGUMENT` fatal error. Web scrapers frequently extract long article texts, HTML blobs, or logs that exceed this threshold. This Actor monitors string lengths and automatically truncates oversized content at 49,900 characters with a clean `... [TRUNCATED]` suffix.
- **Formula Injection Safeguard**: To prevent spreadsheet formula injection vulnerabilities, any string beginning with `=`, `+`, `-`, or `@` is sanitized so spreadsheet software treats it as plain text rather than executing arbitrary macros.
- **Credential Encryption at Rest (`isSecret: true`)**: All private keys and service account JSONs are encrypted at rest with Apify's public key encryption, preventing credentials from leaking in Key-Value Store records or web interfaces.

***

### ❓ Frequently Asked Questions (FAQ)

##### Can I read a Google Sheet without setting up a Google Cloud project?

Yes! If your sheet is shared with *"Anyone with the link can view"*, leave `publicSheet: true` enabled and paste the URL. The Actor uses zero-auth streaming CSV parsing to import rows directly into your dataset without any Google credentials.

##### How does UPSERT matching work?

In `UPSERT` mode, the Actor inspects the column matching your `upsertKey` (e.g. `id`, `sku`, `url`). It indexes existing row values, compares each incoming dataset record, updates matching rows in-place, and appends net-new records to the bottom.

##### What happens if incoming records have different or new columns?

The Actor implements **Dynamic Header Reconciliation**. In `APPEND` and `UPSERT` modes, existing columns are preserved. If a new field appears in your dataset (e.g. `author.twitter`), a new header column is automatically appended to the right and populated.

##### Why do you use Service Accounts instead of OAuth?

Google OAuth tokens expire after 1 hour or require manual re-authentication prompts, causing automated nightly scraper runs to fail. Google Cloud Service Accounts use cryptographic key pairs that never expire, ensuring 100% reliable 24/7 background automation.

##### Are my service account credentials safe?

Yes. Both `serviceAccountPrivateKey` and `serviceAccountJson` are marked with `"isSecret": true` in the Actor's input schema. Apify automatically encrypts them at rest in the default Key-Value Store (`INPUT`), ensuring they are never exposed to viewers or third parties.

##### How does pricing work?

This Actor uses Apify's **Pay-Per-Event (PPE)** pricing at **$0.0005 per row processed** ($0.50 per 1,000 rows). Platform compute is covered by the creator, meaning you never pay compute surcharges for idle waiting or rate-limit backoffs.

***

### ⚖️ Legal & Privacy Compliance

Google Sheets Integration is an automated bridge tool designed for processing user-authorized datasets and spreadsheets.

- It does not store user data beyond the temporary lifecycle of your Apify run.
- All communications with Google Sheets API v4 occur over encrypted HTTPS connections using Google's official client libraries.
- Users are responsible for complying with the [Apify Terms of Service](https://apify.com/terms-of-service) and Google API Services User Data Policy.

# Actor input Schema

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

Choose whether to import a Google Sheet into an Apify dataset (Read), or export an Apify dataset into Google Sheets (Write / Upsert).

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

Enter the full Google Sheets URL or the unique Spreadsheet ID from the URL (e.g. 1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms).

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

Name of the sheet tab inside the spreadsheet (e.g. 'Sheet1', 'Leads', 'Products'). Automatically created on export if missing.

## `publicSheet` (type: `boolean`):

Keep enabled when importing from any Google Sheet shared with 'Anyone with the link can view'. Reads the sheet instantly without requiring any Google Service Account credentials.

## `serviceAccountEmail` (type: `string`):

Leave blank if Public Sheet Mode is enabled. Enter your Google Cloud Service Account client email only for private spreadsheets or exports.

## `serviceAccountPrivateKey` (type: `string`):

Leave blank if Public Sheet Mode is enabled. Enter your private key (starting with -----BEGIN PRIVATE KEY-----) only for private spreadsheets or exports.

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

Leave blank if Public Sheet Mode is enabled. Alternatively paste your entire service-account.json file here.

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

The ID of the Apify Dataset to export. If left empty, it will read from the most recent run or sample items.

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

APPEND: Adds rows below existing data.
OVERWRITE: Clears sheet and writes fresh snapshot.
UPSERT: Matches by primary key to update existing rows and append new ones.

## `upsertKey` (type: `string`):

Column name used as the unique identifier when Write Mode is set to UPSERT (e.g. 'id', 'url', 'email', 'sku').

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

List of specific property names to export as columns. If empty, all properties in the dataset items will be automatically detected and exported.

## `flattenNestedObjects` (type: `boolean`):

If enabled, nested objects are flattened into dot-notated columns (e.g. 'author.name', 'specs.dimensions.width') rather than stringified objects.

## `flattenDelimiter` (type: `string`):

Character used to join nested keys (default is period '.'). E.g. '.' produces 'address.city', '\_' produces 'address_city'.

## `formatSheet` (type: `boolean`):

Automatically freeze the top header row and apply bold text formatting for clean presentation.

## `headerRowIndex` (type: `integer`):

The 1-indexed row number containing column names (default is 1).

## `inferTypes` (type: `boolean`):

Automatically parse numeric strings into numbers, 'TRUE'/'FALSE' into booleans, and ISO strings into date objects.

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

Maximum number of rows to import or export in this run. Prevents runaway memory consumption or API quota exhaustion.

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

Number of rows per batched Google Sheets API request. 500 rows per batch delivers optimal throughput while avoiding payload limits.

## Actor input object example

```json
{
  "mode": "IMPORT_FROM_SHEET",
  "spreadsheet": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit",
  "sheetName": "Class Data",
  "publicSheet": true,
  "serviceAccountEmail": "",
  "datasetId": "",
  "writeMode": "APPEND",
  "upsertKey": "id",
  "fields": [],
  "flattenNestedObjects": true,
  "flattenDelimiter": ".",
  "formatSheet": true,
  "headerRowIndex": 1,
  "inferTypes": true,
  "maxRows": 10000,
  "batchSize": 500
}
```

# Actor output Schema

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

Access all processed items, imported sheet rows, or export summary logs directly.

## `keyValueStore` (type: `string`):

View the run telemetry, rows processed count, and Google Sheets destination link in Key-Value Store.

# 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_FROM_SHEET",
    "spreadsheet": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit",
    "sheetName": "Class Data",
    "publicSheet": true,
    "serviceAccountEmail": "",
    "datasetId": "",
    "writeMode": "APPEND",
    "upsertKey": "id",
    "fields": [],
    "flattenNestedObjects": true,
    "flattenDelimiter": ".",
    "formatSheet": true,
    "headerRowIndex": 1,
    "inferTypes": true,
    "maxRows": 10000,
    "batchSize": 500
};

// Run the Actor and wait for it to finish
const run = await client.actor("vnx0/google-sheets-integration").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_FROM_SHEET",
    "spreadsheet": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit",
    "sheetName": "Class Data",
    "publicSheet": True,
    "serviceAccountEmail": "",
    "datasetId": "",
    "writeMode": "APPEND",
    "upsertKey": "id",
    "fields": [],
    "flattenNestedObjects": True,
    "flattenDelimiter": ".",
    "formatSheet": True,
    "headerRowIndex": 1,
    "inferTypes": True,
    "maxRows": 10000,
    "batchSize": 500,
}

# Run the Actor and wait for it to finish
run = client.actor("vnx0/google-sheets-integration").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_FROM_SHEET",
  "spreadsheet": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit",
  "sheetName": "Class Data",
  "publicSheet": true,
  "serviceAccountEmail": "",
  "datasetId": "",
  "writeMode": "APPEND",
  "upsertKey": "id",
  "fields": [],
  "flattenNestedObjects": true,
  "flattenDelimiter": ".",
  "formatSheet": true,
  "headerRowIndex": 1,
  "inferTypes": true,
  "maxRows": 10000,
  "batchSize": 500
}' |
apify call vnx0/google-sheets-integration --silent --output-dataset

```

## MCP server setup

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

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/pmj4TGepCovArdbmo/builds/rI5VKmOJ39Z1upWup/openapi.json
