> ## Documentation Index
> Fetch the complete documentation index at: https://developers.scoutworks.app/llms.txt
> Use this file to discover all available pages before exploring further.

# Bring members over from a spreadsheet

> Move the young people on an old spreadsheet into Scoutworks, a row at a time, with dropdowns so every section and patrol is one Scoutworks knows.

> [!NOTE]
>
> * **For:** group admins moving to Scoutworks from a spreadsheet
> * **You get:** each row added as a member, in the right section and patrol, with its Scoutworks id
> * **Time:** about twenty minutes
> * **Scopes:** `members:read`, `members.contacts:read` and `members:write`

Moving to Scoutworks from a spreadsheet? This recipe adds each row of a Google Sheet as a member, in the right section and patrol. Each row gets the member's id back, so running it again never adds anyone twice. It takes about twenty minutes, most of it tidying the sheet.

It is for a **group admin**. Try it on one test row first: see [step 5](#5-try-one-row-then-the-rest).

## 1. Create a key

In Scoutworks, open **Settings → Integrations → API keys** and create a key called **Spreadsheet import**, with the scopes **`members:read`**, **`members.contacts:read`** and **`members:write`**. Copy the key: you see it once.

Members the sheet adds show you as the person who added them, and Scoutworks records the key on each one. **Parents are not emailed.** Invite them from Scoutworks when you are ready.

## 2. Lay out the sheet

Make a tab called **Import** with these columns, in this order:

| A | B | C | D | E | F | G | H | I |
| - | - | - | - | - | - | - | - | - |
| First name | Last name | Date of birth | Section | Patrol | Parent first name | Parent last name | Parent email | Scoutworks id |

Format column C as **Format → Number → Date**. Leave column I empty: the script fills it in.

## 3. Add the script and the dropdowns

**1. Paste the script**

Choose **Extensions → Apps Script**, delete what is there, paste the script below and choose **Save**.

**2. Add your key**

Choose **Project Settings → Script Properties → Add script property**. **Property:** `SCOUTWORKS_API_KEY`. **Value:** your key.

**3. Fill the dropdowns**

Back in the sheet, reload it. Choose **Scoutworks → Load sections and patrols**. The script adds a **Lists** tab with your sections and patrols from Scoutworks, and turns columns D and E into dropdowns of them. Pick from the dropdowns rather than typing: a section Scoutworks does not know cannot be imported.

```javascript Code.gs theme={null}
// Spreadsheet → Scoutworks members.
// https://developers.scoutworks.app/recipes/members-from-a-spreadsheet

const BASE = 'https://api.scoutworks.app/api/v1';

function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu('Scoutworks')
    .addItem('Load sections and patrols', 'loadLists')
    .addItem('Add the first row not yet added', 'importOne')
    .addItem('Add every row not yet added', 'importAll')
    .addToUi();
}

function call(method, path, body, key) {
  const res = UrlFetchApp.fetch(BASE + path, {
    method: method,
    contentType: 'application/json',
    headers: Object.assign(
      { Authorization: 'Bearer ' + PropertiesService.getScriptProperties().getProperty('SCOUTWORKS_API_KEY') },
      key ? { 'Idempotency-Key': key } : {}
    ),
    payload: body ? JSON.stringify(body) : undefined,
    muteHttpExceptions: true,
  });
  return { status: res.getResponseCode(), body: JSON.parse(res.getContentText()) };
}

// The Lists tab: one row per section, then one per patrol, with their ids.
function loadLists() {
  const book = SpreadsheetApp.getActive();
  const lists = book.getSheetByName('Lists') || book.insertSheet('Lists');
  const sections = call('get', '/sections?limit=200').body.data.filter(function (s) {
    return s.active;
  });
  const rows = [['Section', 'Section id', 'Patrol', 'Patrol id']];
  sections.forEach(function (s) {
    rows.push([s.name, s.id, '', '']);
    s.patrols.forEach(function (p) {
      rows.push([s.name, s.id, p.name, p.id]);
    });
  });
  lists.clear();
  lists.getRange(1, 1, rows.length, 4).setValues(rows);

  const sheet = book.getSheetByName('Import');
  const rule = function (column) {
    return SpreadsheetApp.newDataValidation()
      .requireValueInRange(lists.getRange(2, column, rows.length - 1, 1), true)
      .setAllowInvalid(false)
      .build();
  };
  sheet.getRange('D2:D').setDataValidation(rule(1));
  sheet.getRange('E2:E').setDataValidation(rule(3));
}

function idOf(listColumn, name, section) {
  const rows = SpreadsheetApp.getActive().getSheetByName('Lists').getDataRange().getValues();
  const match = rows.find(function (r) {
    return listColumn === 0 ? r[0] === name && !r[2] : r[0] === section && r[2] === name;
  });
  return match ? match[listColumn + 1] : null;
}

// A short fingerprint of what a row sends. The same row sends the same key,
// so a retry after a timeout cannot add a twin; a corrected row gets a new
// key, so it is added afresh.
function fingerprint(body) {
  const bytes = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, JSON.stringify(body));
  return Utilities.base64EncodeWebSafe(bytes).slice(0, 22);
}

function importRow(sheet, i, row) {
  const [first, last, dob, section, patrol, parentFirst, parentLast, parentEmail] = row;
  const body = {
    firstName: String(first).trim(),
    lastName: String(last).trim(),
    sectionIds: [idOf(0, section)],
  };
  if (patrol) body.patrolId = idOf(2, patrol, section);
  if (dob instanceof Date) body.dateOfBirth = Utilities.formatDate(dob, 'Europe/London', 'yyyy-MM-dd');
  if (parentEmail) {
    body.parents = [{ firstName: String(parentFirst), lastName: String(parentLast), email: String(parentEmail).trim() }];
  }

  // The row and what it says: re-running a row that timed out cannot add a
  // twin, and a row you corrected is sent as new.
  const key = 'sheet-row-' + (i + 1) + '-' + fingerprint(body);
  const res = call('post', '/members', body, key);
  if (res.status === 201 || res.status === 200) {
    sheet.getRange(i + 1, 9).setValue(res.body.data.id);
  } else if (res.body.error.code === 'possible_duplicate') {
    // Someone with this name is in Scoutworks already. Check before adding.
    sheet.getRange(i + 1, 9).setValue('Check: ' + res.body.matchingIds.join(', '));
  } else {
    sheet.getRange(i + 1, 9).setValue('Error: ' + res.body.error.message);
  }
}

function pending() {
  const sheet = SpreadsheetApp.getActive().getSheetByName('Import');
  const rows = sheet.getDataRange().getValues();
  return { sheet: sheet, rows: rows, todo: rows.map((r, i) => i).filter((i) => i > 0 && rows[i][0] && !rows[i][8]) };
}

function importOne() {
  const p = pending();
  if (p.todo.length) importRow(p.sheet, p.todo[0], p.rows[p.todo[0]]);
}

function importAll() {
  const p = pending();
  p.todo.forEach(function (i) {
    importRow(p.sheet, i, p.rows[i]);
    Utilities.sleep(2100); // The API takes 30 changes a minute.
  });
}
```

## 4. Check the sheet

* Every row has a first name, a last name and a section from the dropdown.
* Dates of birth are real dates, not text. A date in the future is refused.
* Each parent email is spelt right. A parent with the same email on two rows is linked to both children, as one person.

## 5. Try one row, then the rest

**1. Add one row**

Choose **Scoutworks → Add the first row not yet added**. Column I fills with the member's id. Open the member in Scoutworks and check the section, patrol and parent.

**2. Add the rest**

Choose **Scoutworks → Add every row not yet added**. The script adds about 28 rows a minute. A large sheet may stop after six minutes, Google's limit for one run: choose it again and it carries on where it stopped.

If the test row was wrong, archive that member in Scoutworks, fix the row, clear its column I and add it again. The corrected row is sent as a new request. Sent unchanged within 24 hours, it would answer with the member you archived: restore them in Scoutworks instead.

## Rows that say "Check"

The API answered `409 possible_duplicate`: Scoutworks already has a member with this name and date of birth, or this name and parent email. Column I lists their ids. Look them up in Scoutworks. If the row really is a different young person, the script can add it anyway: change `'/members'` to `'/members' + '?allowDuplicate=true'` in `importRow`, add that row, then change it back.

See [Errors](https://developers.scoutworks.app/guides/errors.md) for every code.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.