# Google Sheets Import & Export (Reliable, Service Account) (`zangado/google-sheets-reliable`) Actor

Read, append or replace Google Sheets rows from any Apify dataset or JSON. Service-account auth that never expires, public sheets without login, auto columns, batches for large data.

- **URL**: https://apify.com/zangado/google-sheets-reliable.md
- **Developed by:** [Josicleuton da Silva Braga](https://apify.com/zangado) (community)
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.05 / 1,000 row read or 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 Import & Export (Reliable, Service Account)

**Read, append or replace Google Sheets rows** from any Apify dataset or JSON — with **service-account authentication that never expires** and never needs a browser login. Built for scheduled pipelines, scrapers and AI agents that must not break at 3 a.m.

### Why this Actor

- 🔐 **Service account auth** — no OAuth popups, no tokens expiring, no "app blocked by Google" errors.
- 🌐 **Public sheets without any login** — just paste the link.
- ➕ **Append** under the existing header; **new fields become new columns automatically** (existing column order is kept).
- ♻️ **Replace** a whole tab in one run (great for daily exports).
- 🧩 **Nested JSON is flattened** to dotted columns (`user.name`), lists are stored as JSON text.
- 📦 **Batches for large data** (1,000 rows per request) to stay within Google limits.
- 🛡️ **Safe by default** — values are written `RAW`, so text like `=IMPORTXML(...)` is never executed as a formula unless you choose `USER_ENTERED`.
- 💬 **Clear error messages** that tell you exactly what to fix (sharing, tab name, key format).

### Quick start

#### Read a public sheet (no setup)

```json
{
  "spreadsheet": "https://docs.google.com/spreadsheets/d/<ID>/edit#gid=0",
  "operation": "read"
}
```

Each row becomes one dataset item, using the first row as the header.

#### Write rows (append or replace)

1. In Google Cloud Console create a **service account** and a **JSON key** (free). Enable the **Google Sheets API** for the project.
2. Open your spreadsheet → **Share** → add the service account email (`...@...iam.gserviceaccount.com`) as **Editor**.
3. Run:

```json
{
  "spreadsheet": "https://docs.google.com/spreadsheets/d/<ID>/edit",
  "operation": "append",
  "sheetName": "Leads",
  "datasetId": "<APIFY_DATASET_ID>",
  "serviceAccountJson": "{ ...paste the key file... }"
}
```

The key is stored **encrypted** by Apify (secret input).

### Input

| Field | Description | Default |
|---|---|---|
| `spreadsheet` | Sheet URL or ID (a tab URL with `#gid=` selects that tab) | — |
| `operation` | `read`, `append`, `replace` | `read` |
| `serviceAccountJson` | Service account key (needed to write or read private sheets) | — |
| `sheetName` | Tab name (created automatically on write if missing) | first tab |
| `datasetId` | Apify dataset to write | — |
| `rows` | Array of objects to write (alternative to `datasetId`) | — |
| `columns` | Only these columns, in this order | all |
| `valueInputOption` | `RAW` (safe) or `USER_ENTERED` | `RAW` |
| `maxRows` | Upper limit per run | 100000 |

### Output

- **Read:** one item per row, e.g. `{ "Name": "Ana", "Age": "30" }`.
- **Append / Replace:** one summary item `{ "operation": "append", "rowsWritten": 250, "sheet": "Leads" }`.

### Pricing (pay per event)

You pay a small fee per row read or written plus a tiny start fee per run. Failed runs with a configuration error write nothing and charge no rows.

### Integrations

Chain it after any scraper with Apify **Integrations → Run Actor** (pass the scraper's `defaultDatasetId` as `datasetId`), or call it from n8n, Make, Zapier, LangChain or an AI agent through the Apify MCP server.

### Troubleshooting

- *"Cannot open the spreadsheet"* → share the sheet with the service account email.
- *"This spreadsheet is not public"* → set sharing to "Anyone with the link can view" or use a service account.
- *"Reading a tab by name needs serviceAccountJson"* → for public sheets paste the tab URL (contains `#gid=`).

# Actor input Schema

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

Paste the Google Sheets URL (a tab URL with #gid=... selects that tab) or the spreadsheet ID.

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

Read rows into the dataset, append rows to the sheet, or replace the whole tab.

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

Google Cloud service account key file content. Required to write, or to read private sheets. Share the spreadsheet with the service account email (Editor to write). Stored encrypted.

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

Optional. Tab to read/write (created on append/replace if missing). Requires the service account.

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

Apify dataset whose items will be written to the sheet (name or ID).

## `rows` (type: `array`):

Alternative to datasetId: array of objects. Nested objects become dotted columns (e.g. user.name).

## `columns` (type: `array`):

Write only these columns, in this order.

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

RAW writes text exactly as given (safe default). USER_ENTERED lets Google parse numbers, dates and formulas.

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

Upper limit of rows read or written in one run (protects your budget).

## Actor input object example

```json
{
  "spreadsheet": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit#gid=0",
  "operation": "read",
  "valueInputOption": "RAW",
  "maxRows": 100000
}
```

# Actor output Schema

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

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

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

```

## MCP server setup

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

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/aA3wC6EmavCUnfUgB/builds/mYmALoq0h6NE40hmP/openapi.json
