# Export to Google Sheets: batched, retried, clear errors (`datosfiables/exportar-google-sheets`) Actor

Exports an Apify dataset or a JSON list to a Google Sheets tab, within Google's quotas, with retries and actionable error messages. Authenticates with a service account, so no interactive login is needed.

- **URL**: https://apify.com/datosfiables/exportar-google-sheets.md
- **Developed by:** [Datos Fiables](https://apify.com/datosfiables) (community)
- **Features:** Limited permissions
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$5.00 / 1,000 export completeds

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

## Export to Google Sheets: batched, retried, clear errors

Send an **Apify dataset** or a **JSON list** to a **Google Sheets** tab, without hitting Google's quotas and without an interactive Google login.

- **Batched writes** with a minimum gap between requests, to stay under Google's per-minute limit.
- **Automatic retries** on `429` and `5xx` errors, honouring `Retry-After`.
- **Service account** authentication: works unattended, in schedules, integrations and AI agents.
- **Checks before writing**: the tab exists and the sheet stays under Google's 10 million cell limit.
- **Clear errors**: every failure returns a stable `codigo`, a `mensaje` and a `solucion` that says how to fix it.
- **Values are written as-is** (`RAW`): `00123` stays `00123`, `1-2` is not turned into a date, `=SUM()` is not executed.

### Pricing

**$0.005 per completed export**, plus a tiny amount of platform compute (default memory 512 MB).
Runs that fail are **not charged**.

### How to use it

1. **Create a service account key** (free, one time):
   - In [Google Cloud Console](https://console.cloud.google.com/) create a project and enable the **Google Sheets API**.
   - Go to **IAM & Admin → Service accounts → Create service account**, then **Keys → Add key → JSON**. A `.json` file is downloaded.
2. **Share your spreadsheet** as **Editor** with the `client_email` from that file (it ends in `iam.gserviceaccount.com`).
3. **Run the Actor** with the spreadsheet URL, the contents of the JSON key and either a `datasetId` or `data`.

Tip: to export the results of another Actor automatically, add this Actor as an **integration** of that Actor and pass its default dataset ID.

### Input

| Field | Type | Default | Description |
|---|---|---|---|
| `spreadsheetId` | string | — | Spreadsheet URL or ID. **Required.** |
| `serviceAccountJson` | string (secret) | — | Full JSON key of the service account. **Required.** |
| `datasetId` | string | — | Apify dataset to export. Use this **or** `data`. |
| `data` | array | — | List of JSON objects. Use this **or** `datasetId`. |
| `sheetName` | string | first tab | Exact tab name. |
| `mode` | `append` | `replace` | `append` | Add rows at the end, or clear the tab first. |
| `writeHeaders` | boolean | `true` | Write column names if the tab is empty. |
| `maxRows` | integer | `50000` | Maximum rows to export (up to 1,000,000). |

Example:

```json
{
  "spreadsheetId": "https://docs.google.com/spreadsheets/d/YOUR_ID/edit",
  "serviceAccountJson": "{ \"type\": \"service_account\", ... }",
  "datasetId": "YOUR_DATASET_ID",
  "sheetName": "Data",
  "mode": "append"
}
```

### Output

One item in the default dataset per run.

Success:

```json
{
  "estado": "ok",
  "hoja": "My spreadsheet",
  "pestana": "Data",
  "modo": "append",
  "filasEscritas": 1200,
  "cabecerasEscritas": true,
  "columnas": ["name", "age", "city"],
  "lotes": 1,
  "avisos": [],
  "peticionesAGoogle": 3,
  "reintentos": 0,
  "fuente": "https://docs.google.com/spreadsheets/d/YOUR_ID/edit#gid=0",
  "actualizado": "2026-11-02T10:00:00.000Z"
}
```

Error (the run is marked as failed and is not charged):

```json
{
  "estado": "error",
  "codigo": "SIN_PERMISOS",
  "mensaje": "Google denegó el acceso a la hoja (403).",
  "solucion": "Abre la hoja, pulsa Compartir y añade el email de la cuenta de servicio (campo client_email) como Editor. ...",
  "actualizado": "2026-11-02T10:00:00.000Z",
  "fuente": "https://developers.google.com/workspace/sheets/api/limits"
}
```

Field names are in Spanish and stable, so agents and integrations can rely on them. `mensaje` and `solucion` are currently in Spanish; the `codigo` table below explains each one in English.

#### Error codes

| `codigo` | Meaning |
|---|---|
| `ENTRADA_INVALIDA` | Missing or wrong input (e.g. both `datasetId` and `data`). |
| `CREDENCIALES_INVALIDAS` | The service account JSON is malformed. |
| `AUTENTICACION_FALLIDA` | Google rejected the key (deleted key or Sheets API not enabled). |
| `SIN_PERMISOS` | The spreadsheet is not shared with the service account. |
| `HOJA_NO_ENCONTRADA` | Wrong spreadsheet URL or ID. |
| `PESTANA_NO_ENCONTRADA` | No tab with that name. |
| `DATASET_NO_ENCONTRADO` | No dataset with that ID or name in your account. |
| `SIN_DATOS` | Nothing to export. |
| `LIMITE_CELDAS` | The export would exceed Google's 10M cell limit. |
| `CUOTA_SUPERADA` | Google's quota was still exceeded after retries. |
| `ERROR_GOOGLE` | Other error returned by Google. |
| `ERROR_INESPERADO` | Anything else; retry, and report it with the run ID if it persists. |

### Limitations

- Does not create spreadsheets or tabs, and does not format cells.
- Rows are loaded into memory: up to `maxRows` (50,000 by default).
- `replace` clears the tab before writing. If a later batch fails, the tab is left partially written (the error says so and how many rows were written).
- An interrupted export is not resumed.

### Privacy

Your data and key go only from Apify to Google's official Sheets API. The key is a secret input: it is stored encrypted and never logged.

### Questions or bugs

Open an issue in the **Issues** tab of this Actor. Include the run ID.

# Actor input Schema

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

Full URL or ID of the spreadsheet. Share it as Editor with the service account email (client_email in the key file).

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

Full contents of a Google service account JSON key, with the Google Sheets API enabled in its project. Stored encrypted and never printed in logs.

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

Dataset to read rows from (ID or name). Fill this or "data", not both.

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

List of JSON objects, e.g. \[{"name":"Ana","age":30}]. Alternative to datasetId for small exports.

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

Exact name of the tab. Leave empty to use the first tab.

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

"append" adds rows at the end; "replace" clears the tab and writes again.

## `writeHeaders` (type: `boolean`):

Writes column names in the first row if the tab is empty. If headers already exist, rows are aligned to them.

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

Maximum number of rows to export (protects cost and quotas).

## Actor input object example

```json
{
  "spreadsheetId": "https://docs.google.com/spreadsheets/d/1AbCdEfGhIjKlMnOpQrStUvWxYz0123456789/edit",
  "datasetId": "",
  "sheetName": "",
  "mode": "append",
  "writeHeaders": true,
  "maxRows": 50000
}
```

# 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 = {
    "spreadsheetId": "https://docs.google.com/spreadsheets/d/1AbCdEfGhIjKlMnOpQrStUvWxYz0123456789/edit",
    "datasetId": ""
};

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

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

```

## MCP server setup

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

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/ooY5vv0xBAaBtexJx/builds/ubO9ADVmD03hpyyac/openapi.json
