# Google Sheets Export & Import (No Google Account Linking) (`yaroslav1/google-sheets-export`) Actor

Google Sheets integration for Apify: export any dataset to a Google Sheet after every run, or import a tab into a dataset. Works through a small script in your own spreadsheet: no Google account linking, no Cloud project, no API keys. Append, replace, or add only new rows.

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

## Pricing

from $0.07 / 1,000 rows

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

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 Export & Import

Send any Apify dataset to a Google Sheet, by hand or automatically after every run of another Actor. Or import a tab of a Google Sheet into a dataset.

It works through a small script that you paste into **your own spreadsheet** once. Your Google account is never connected to Apify: no "Sign in with Google" on Apify, no Google Cloud project, no service-account keys.

### Why use it

- **A setup that keeps working.** There is no Google authorization on Apify that can expire or fail. You paste a script into your sheet once (about 3 minutes) and the Actor talks to it.
- **Access to one spreadsheet only.** The script can open only the spreadsheet it lives in (Google's `@OnlyCurrentDoc` rule), not the rest of your Google Drive.
- **Append, replace, or add only new rows.** Skip rows whose `url` or `id` is already in the sheet, so scheduled scrapers never create duplicates.
- **Values stay exact.** Leading zeros (`000123`), long IDs, phone numbers (`+1 555 0100`) and dates stay as they were scraped; numbers stay numbers. Scraped text is never run as a formula.
- **Nested data like Apify's CSV export:** `seller/name`, `images/0`, `images/1`, or one JSON cell per field if you prefer.
- **New columns are added automatically** on the right. Your existing columns and rows are left as they are.
- **Clear error messages** that say exactly what to fix in Google.
- **Pay only for rows written.** Rows skipped because they are already in the sheet are not charged, and a "Check only" run tests your settings without writing anything.

### Set up once (about 3 minutes)

> **Tip:** run this Actor once with an empty input. It gives you a setup page with the script below and a random token already filled in.

1. Open your spreadsheet in Google Sheets and choose **Extensions → Apps Script**.
2. Click into the code you see there, press **Ctrl+A** (Mac: **⌘A**) and paste the script below over it, so nothing else stays in the file (no `function myFunction() {` around it). Change the `TOKEN` line to your own secret of 16 or more letters and digits. Press **Save**.
3. Choose **Deploy → New deployment**, click the gear icon and pick **Web app**. Set **Execute as: Me** and **Who has access: Anyone**, then press **Deploy**.
4. Press **Authorize access** and pick your Google account. If Google says that it hasn't verified the app, choose **Advanced → Go to … (unsafe)**. It is your own script, and it can open only this spreadsheet.
5. Copy the **Web app URL** (it ends with `/exec`). In this Actor, paste it into **Web app URL**, and paste your secret into **Token**.

"Who has access: Anyone" lets the Actor reach the script without a Google sign-in. Nobody can write to your sheet without both the Web app URL and the token, so keep them private. To switch the bridge off at any time, open **Deploy → Manage deployments** and archive the deployment.

```javascript
/**
 * Apify -> Google Sheets bridge, version 1.
 *
 * How to connect (about 3 minutes):
 *  1. Change TOKEN below to your own secret (16+ letters and digits) and put the same secret
 *     into the robot's "Token" field.
 *  2. Save (Ctrl+S). Then Deploy -> New deployment -> Select type: Web app.
 *     Execute as: Me. Who has access: Anyone. Press Deploy and allow access.
 *  3. Copy the Web app URL (it ends with /exec) into the robot's "Web app URL" field.
 * After any change to this code, deploy again:
 *     Deploy -> Manage deployments -> Edit (pencil) -> Version: New version -> Deploy.
 *
 * Safety: the line below lets this script open only THIS spreadsheet, none of your other files.
 * Writing here needs both the URL and the token, so keep them private.
 * @OnlyCurrentDoc
 */
const TOKEN = 'PASTE-YOUR-OWN-SECRET-HERE';

const BRIDGE_VERSION = 1;
const MAX_CELL_CHARS = 50000;

function doGet() {
  return reply_({ ok: true, bridge: 'apify-sheets', version: BRIDGE_VERSION, message: 'The bridge works. Paste this URL into the robot.' });
}

function doPost(e) {
  let req;
  try {
    req = JSON.parse(e && e.postData ? e.postData.contents : '');
  } catch (err) {
    return reply_({ ok: false, error: 'bad-request', message: 'The request is not valid JSON.' });
  }
  if (TOKEN.length < 16 || TOKEN.indexOf('PASTE-') === 0) {
    return reply_({ ok: false, error: 'token-not-set', message: 'Set your own TOKEN (16+ characters) at the top of the script, save, and deploy a new version.' });
  }
  if (!req || req.token !== TOKEN) {
    return reply_({ ok: false, error: 'bad-token', message: 'The token does not match TOKEN in the script.' });
  }
  const lock = LockService.getScriptLock();
  if (!lock.tryLock(30000)) {
    return reply_({ ok: false, error: 'busy', message: 'Another export is writing to this spreadsheet right now.' });
  }
  try {
    // A repeated request (the robot retries after a network error) gets the saved answer instead of writing twice.
    const cache = CacheService.getScriptCache();
    const cacheKey = req.requestId ? 'apify-req-' + String(req.requestId).slice(0, 200) : '';
    const saved = cacheKey ? cache.get(cacheKey) : null;
    if (saved) return reply_(JSON.parse(saved));
    const res = handle_(req);
    if (cacheKey && res.ok && (req.action === 'append' || req.action === 'clear')) {
      try {
        cache.put(cacheKey, JSON.stringify(res), 21600);
      } catch (err) {
        // The answer is still returned; only the retry protection is skipped.
      }
    }
    return reply_(res);
  } catch (err) {
    return reply_({ ok: false, error: 'script-error', message: String(err && err.message ? err.message : err) });
  } finally {
    lock.releaseLock();
  }
}

function handle_(req) {
  const ss = SpreadsheetApp.getActive();
  if (!ss) {
    return { ok: false, error: 'no-spreadsheet', message: 'Create this script from inside the spreadsheet: Extensions -> Apps Script.' };
  }
  const name = String(req.sheet || 'Apify').trim().slice(0, 100) || 'Apify';
  let sheet = ss.getSheetByName(name);
  const res = { ok: true, version: BRIDGE_VERSION, spreadsheet: { name: ss.getName(), url: ss.getUrl() } };

  if (req.action === 'info' || req.action === 'read') {
    res.sheet = info_(sheet, name);
    res.sheets = ss.getSheets().map(function (s) { return s.getName(); });
    if (req.action === 'info') return res;
    res.header = res.sheet.header;
    res.rows = [];
    res.done = true;
    if (!sheet) return res;
    const lastRow = res.sheet.lastRow;
    const lastCol = res.sheet.lastColumn;
    const offset = Math.max(0, Math.floor(Number(req.offset) || 0));
    const limit = Math.min(5000, Math.max(1, Math.floor(Number(req.limit) || 1000)));
    const first = 2 + offset;
    const count = Math.min(limit, lastRow - first + 1);
    if (count > 0 && lastCol > 0) {
      const tz = ss.getSpreadsheetTimeZone();
      res.rows = sheet.getRange(first, 1, count, lastCol).getValues().map(function (row) {
        return row.map(function (v) { return plain_(v, tz); });
      });
    }
    res.done = first + Math.max(count, 0) > lastRow;
    return res;
  }

  if (!sheet) sheet = ss.insertSheet(name);

  if (req.action === 'clear') {
    sheet.clearContents();
    res.sheet = info_(sheet, name);
    return res;
  }
  if (req.action === 'append') return append_(sheet, req, res);
  return { ok: false, error: 'bad-action', message: 'Unknown action: ' + req.action };
}

// Row 1 is the header. Columns that a batch needs and the tab does not have yet are added on the right,
// then the rows go below the last used row.
function append_(sheet, req, res) {
  const names = (req.columns || []).map(String);
  const rows = req.rows || [];
  const lastCol = sheet.getLastColumn();
  const header = sheet.getLastRow() > 0 && lastCol > 0 ? sheet.getRange(1, 1, 1, lastCol).getDisplayValues()[0] : [];
  const pos = new Map();
  header.forEach(function (h, i) { if (h !== '' && !pos.has(h)) pos.set(h, i); });
  const added = [];
  names.forEach(function (n) {
    if (!pos.has(n)) {
      pos.set(n, header.length + added.length);
      added.push(n);
    }
  });
  if (added.length) {
    const start = header.length + 1;
    grow_(sheet, 1, header.length + added.length);
    // The apostrophe keeps a header such as "2024" or "=x" as plain text; it is not stored in the cell.
    sheet.getRange(1, start, 1, added.length).setValues([added.map(function (n) { return "'" + n; })]);
    if (start === 1) {
      sheet.getRange(1, 1, 1, added.length).setFontWeight('bold');
      if (sheet.getFrozenRows() === 0) sheet.setFrozenRows(1);
    }
  }
  const width = header.length + added.length;
  const idx = names.map(function (n) { return pos.get(n); });

  // Skip rows whose unique key is already in the tab (or earlier in this batch).
  let seen = null;
  let keyIdx = -1;
  if (req.uniqueKey) {
    keyIdx = names.indexOf(String(req.uniqueKey));
    if (keyIdx >= 0) {
      seen = new Set();
      const last = sheet.getLastRow();
      if (last > 1) {
        sheet.getRange(2, pos.get(names[keyIdx]) + 1, last - 1, 1).getValues().forEach(function (r) { seen.add(key_(r[0])); });
      }
    }
  }

  const out = [];
  let skipped = 0;
  rows.forEach(function (r) {
    if (seen) {
      const k = key_(r[keyIdx]);
      if (k !== '') {
        if (seen.has(k)) {
          skipped++;
          return;
        }
        seen.add(k);
      }
    }
    const line = new Array(width).fill('');
    for (let i = 0; i < idx.length; i++) line[idx[i]] = cell_(r[i]);
    out.push(line);
  });

  const firstRow = Math.max(sheet.getLastRow(), 1) + 1;
  if (out.length && width > 0) {
    grow_(sheet, firstRow + out.length - 1, width);
    sheet.getRange(firstRow, 1, out.length, width).setValues(out);
  }
  const written = width > 0 ? out.length : 0;
  res.written = written;
  res.skipped = skipped;
  res.firstRow = written ? firstRow : null;
  res.lastRow = written ? firstRow + written - 1 : sheet.getLastRow();
  res.columns = width;
  res.added = added;
  return res;
}

function info_(sheet, name) {
  if (!sheet) return { name: name, exists: false, lastRow: 0, lastColumn: 0, header: [] };
  const lastRow = sheet.getLastRow();
  const lastCol = sheet.getLastColumn();
  const header = lastRow > 0 && lastCol > 0 ? sheet.getRange(1, 1, 1, lastCol).getDisplayValues()[0] : [];
  return { name: sheet.getName(), exists: true, lastRow: lastRow, lastColumn: lastCol, header: header };
}

function grow_(sheet, rows, cols) {
  const maxRows = sheet.getMaxRows();
  const maxCols = sheet.getMaxColumns();
  if (rows > maxRows) sheet.insertRowsAfter(maxRows, rows - maxRows);
  if (cols > maxCols) sheet.insertColumnsAfter(maxCols, cols - maxCols);
}

// One value for a cell. Text that Sheets would run as a formula is kept as plain text.
function cell_(v) {
  if (v === null || v === undefined) return '';
  if (typeof v === 'number') return isFinite(v) ? v : String(v);
  if (typeof v === 'boolean') return v;
  let s = typeof v === 'string' ? v : JSON.stringify(v);
  if (/^[=@]/.test(s) || (/^[+\-]/.test(s) && !/^[+\-]?\d+(\.\d+)?$/.test(s))) s = "'" + s;
  return s.length > MAX_CELL_CHARS ? s.slice(0, MAX_CELL_CHARS) : s;
}

// The text a unique-key cell is compared by.
function key_(v) {
  if (v instanceof Date) return isNaN(v.getTime()) ? '' : v.toISOString();
  let s = v === null || v === undefined ? '' : String(v);
  if (s.charAt(0) === "'") s = s.slice(1);
  return s.trim();
}

// A cell value for the robot: dates in the spreadsheet's time zone, empty cells as null.
function plain_(v, tz) {
  if (v instanceof Date) {
    if (isNaN(v.getTime())) return null;
    const time = Utilities.formatDate(v, tz, 'HH:mm:ss');
    return Utilities.formatDate(v, tz, time === '00:00:00' ? 'yyyy-MM-dd' : "yyyy-MM-dd'T'HH:mm:ss");
  }
  return v === '' ? null : v;
}

function reply_(obj) {
  return ContentService.createTextOutput(JSON.stringify(obj)).setMimeType(ContentService.MimeType.JSON);
}
```

### Send results to Google Sheets after every run

1. Open the Actor or task whose results you want in the sheet and go to its **Integrations** tab.
2. Add an integration that runs another Actor, pick **Google Sheets Export & Import** and the event **Run succeeded**.
3. In the input, keep **Dataset** set to `{{resource.defaultDatasetId}}` (the dataset of the run that just finished) and fill in the Web app URL, the token and the tab name.

From now on every successful run lands in your sheet. Put `url` or `id` into **Skip rows already in the sheet, by column** to add only new rows.

### Input

| Field | What it does |
| --- | --- |
| **Web app URL** | The `/exec` link of the script in your spreadsheet. Leave it empty to get the setup page. |
| **Token** | The same secret as in the script's `TOKEN` line. Stored encrypted. |
| **Tab name** | The tab to write to or read from (default `Apify`). It is created when it does not exist. |
| **Mode** | **Append rows** (default) adds rows below the existing ones. **Replace the tab** clears it, then writes the dataset; an empty dataset leaves the tab untouched. **Import the tab into a dataset** copies the tab into this run's dataset. |
| **Dataset** | The dataset to send. As an integration: `{{resource.defaultDatasetId}}`. |
| **Skip rows already in the sheet, by column** | For example `url` or `id`. Rows whose value is already in that column, or earlier in the dataset, are skipped and not charged. |
| **Only these fields / Leave out these fields** | Choose top-level fields, for example leave out long `html` fields. |
| **Nested data** | **Columns** like Apify's CSV export (`address/city`, `images/0`), or **JSON** text in one cell. |
| **Text values** | **Smart** (default): text such as `"19.99"` becomes a number, everything else stays exactly as it is. **Keep all text as text.** **Like typing into Google Sheets**: Sheets turns text into dates, percents and currencies based on the spreadsheet's locale. |
| **Max rows** | Stop after this many rows. |
| **Check only** | Test the connection and the token and see the first rows as they will look, without writing anything. |

### Output

In **Append** and **Replace** modes the run's dataset gets one summary row:

```json
{
  "recordType": "summary",
  "mode": "append",
  "spreadsheetName": "Competitor prices",
  "spreadsheetUrl": "https://docs.google.com/spreadsheets/d/…/edit",
  "sheetName": "Apify",
  "itemsRead": 1250,
  "rowsWritten": 1180,
  "rowsSkipped": 70,
  "columns": 14,
  "newColumns": ["seller/rating"],
  "firstRow": 2402,
  "lastRow": 3581,
  "stoppedBy": null
}
```

In **Import** mode the dataset holds the rows of the tab, one item per row, with the header row (row 1) as field names. Empty cells become `null`, and dates come as `2026-11-10` or `2026-11-10T14:30:00` in the spreadsheet's time zone.

The same numbers are saved as the `SUMMARY` record in the run's key-value store.

### How rows are written

- Row 1 of the tab is the header. Columns are matched by name, so the order of fields in your data does not matter.
- Columns that the sheet does not have yet are added on the right. Existing cells are never changed in Append mode.
- Numbers and true/false values stay numbers and true/false values. With **Smart** text values, text that is a plain number (like `"19.99"`) becomes a number, and all other text is written exactly as it is.
- Text that starts with `=`, `+`, `-` or `@` is written as plain text, so scraped content can never run as a formula in your sheet.
- Google allows 50,000 characters per cell, so longer texts are cut to that length (the summary counts them).
- If the network fails in the middle of a request, the Actor sends it again, and the script makes sure the same rows are not written twice.

### Pricing

You pay per row: one event for each row written to the sheet or imported from it. Rows skipped because they are already in the sheet are not charged, and "Check only" and setup runs charge no rows. See the **Pricing** tab for the price per 1,000 rows. You can also set a maximum cost per run in Apify; the Actor stops before going over it.

### Limits

- Google Sheets allows up to 10 million cells per spreadsheet and 50,000 characters per cell.
- Google stops an Apps Script request after 6 minutes. The Actor sends 1,000 rows per request, which normally takes a few seconds, and splits a request in two if Google ever refuses it.
- Google Workspace (company) accounts: if **Anyone** is not offered in "Who has access", your admin blocks public web apps. Use a spreadsheet in a personal Google account, or ask the admin.
- The daily Apps Script quotas of your Google account apply. They are far above normal use.

### FAQ

**The run says Google asked for a sign-in.** In Apps Script open **Deploy → Manage deployments → Edit** (pencil icon) and set **Who has access** to **Anyone**.

**The run says the token does not match.** The **Token** field and the `TOKEN` line of the script must hold exactly the same text. After you change the script, deploy a new version (next answer).

**I changed the script, but nothing changed.** The Web app URL keeps running the old version until you deploy again: **Deploy → Manage deployments → Edit → Version: New version → Deploy**. The URL stays the same.

**Can I write to several tabs or spreadsheets?** Yes. Use one run or integration per tab. Each spreadsheet needs its own copy of the script and has its own Web app URL.

**Will Replace delete my own formulas?** Replace clears the whole tab before writing (only when the dataset has rows). Keep your own formulas and charts on another tab that refers to this one.

**Is my data sent anywhere else?** No. The Actor reads your dataset on Apify and sends the rows only to your Web app URL on `script.google.com`. It never sees your Google password or any Google token.

This Actor is not affiliated with or endorsed by Google. Google Sheets is a trademark of Google LLC.

# Actor input Schema

## `webAppUrl` (type: `string`):

The link of the bridge script in your spreadsheet. It looks like <code>https://script.google.com/macros/s/…/exec</code>. To get it, paste the script from the README into Extensions → Apps Script, then Deploy → New deployment → Web app (Execute as: Me, Who has access: Anyone). <b>Leave this empty and run once</b> to get a setup page with the script and a personal token.

## `token` (type: `string`):

The same secret as in the TOKEN line at the top of the bridge script (16+ characters).

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

The tab (sheet) of the spreadsheet to write to or read from. It is created when it does not exist yet.

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

<b>Append</b> adds rows below the existing ones and adds new columns on the right. <b>Replace</b> clears the tab, then writes the dataset (an empty dataset leaves the tab as it is). <b>Import</b> copies the tab into this run's dataset.

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

The dataset to send to the sheet. When you add this Actor as an integration of another Actor, this is filled in for you: <code>{{resource.defaultDatasetId}}</code>.

## `uniqueKey` (type: `string`):

A column such as <code>url</code> or <code>id</code>. Rows whose value in this column is already in the tab (or earlier in the dataset) are skipped and not charged. Leave empty to write every row.

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

Send only these top-level fields of the dataset, in this order. Leave empty to send all fields.

## `omitFields` (type: `array`):

Top-level fields not to send, for example long <code>html</code> or <code>text</code> fields.

## `nested` (type: `string`):

How objects and lists inside items become cells. <b>Columns</b> works like Apify's CSV export: <code>address/city</code>, <code>images/0</code>, <code>images/1</code>. <b>JSON</b> keeps each field in one cell as JSON text.

## `textValues` (type: `string`):

<b>Smart</b>: text such as "19.99" becomes a number, everything else stays exactly as it is (leading zeros, long IDs, phone numbers, dates). <b>Text</b>: all text stays text. <b>Like typing</b>: Google Sheets turns text into dates, percents and currencies the way it does when you type, which depends on the spreadsheet's locale. Formulas are never run in any mode.

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

Stop after this many rows. Leave empty for all rows.

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

Test the settings without writing anything: checks the connection and the token, and shows the first rows as they would look in the sheet. No rows are charged.

## Actor input object example

```json
{
  "sheetName": "Apify",
  "mode": "append",
  "nested": "columns",
  "textValues": "smart",
  "dryRun": false
}
```

# Actor output Schema

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

All rows of this run in the default dataset.

# 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("yaroslav1/google-sheets-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("yaroslav1/google-sheets-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 yaroslav1/google-sheets-export --silent --output-dataset

```

## MCP server setup

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