Google Apps Script Quickstart

Complete the steps described in the rest of this page to create a simple Google Apps Script that makes requests to the Google Sheets API.

Prerequisites

To run this quickstart, you need the following prerequisites:

  • A Google account
  • Access to Google Drive

Step 1: Create the script

  1. Create a new script by going to script.google.com/create.
  2. Replace the contents of the script editor with the following code:

sheets/quickstart/quickstart.gs
/**
 * Creates a Sheets API service object and prints the names and majors of
 * students in a sample spreadsheet:
 * https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
 */
function logNamesAndMajors() {
  var spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
  var rangeName = 'Class Data!A2:E';
  var values = Sheets.Spreadsheets.Values.get(spreadsheetId, rangeName).values;
  if (!values) {
    Logger.log('No data found.');
  } else {
    Logger.log('Name, Major:');
    for (var row = 0; row < values.length; row++) {
      // Print columns A and E, which correspond to indices 0 and 4.
      Logger.log(' - %s, %s', values[row][0], values[row][4]);
    }
  }
}

  1. Click File > Save, name your project “Quickstart”, and click OK.

Step 2: Turn on the Google Sheets API

Enable the Google Sheets API advanced service in your script.

Step 3: Run the sample

In the Apps Script editor, click Run > logNamesAndMajors.

The first time you run the sample, it will prompt you to authorize access:

  1. Click the Continue button.
  2. Click the Accept button.

To view the script's output, click View > Logs.

Further reading

Troubleshooting

This section describes some common issues that you may encounter while attempting to run this quickstart and suggests possible solutions.

ReferenceError: "[API NAME]" is not defined

This error occurs when the API hasn't been toggled on in the Apps Script code editor. Revisit Step 2.b and ensure the corresponding toggle is set to on.

This app isn't verified.

The OAuth consent screen that is presented to the user may show the warning "This app isn't verified" if it is requesting scopes that provide access to sensitive user data. These applications must eventually go through the verification process to remove that warning and other limitations. During the development phase you can continue past this warning by clicking Advanced > Go to {Project Name} (unsafe).

Envoyer des commentaires concernant…

Besoin d'aide ? Consultez notre page d'assistance.