LoginSignup
5
12

More than 3 years have passed since last update.

GoogleスプレッドシートのNode.jsクイックスタート

Last updated at Posted at 2019-05-26

はじめに

Googleスプレッドシートをプログラムから操作したくなったので、Node.jsのクイックスタートをやってみました。基本的にはGoogleが公開しているQuickStartの通りにやれば良いのですが、画面やコメント付で補足します。

QuickStart
https://developers.google.com/sheets/api/quickstart/nodejs

このクイックスタートではGoogleが提供するサンプルを実行するだけで、権限設定などは実施しますが、ユーザがAPIのメソッドを意識することはありません=このクイックスタートだけやってもスプレッドシートの操作はできるようになりません。

やること

以下で公開されているGoogleスプレッドシートから、A列Student NameとE列Majorを抽出してコンソール(標準出力)に出力します。対象のスプレッドシートの参照と、列の抽出処理はサンプルファイル内に定義しているのでこのクイックスタートでユーザが意識することはありません。
https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit#gid=0

Googleのクイックスタートでは何をやっているのか説明がないのでわかりづらい。サンプルコードの中では説明しているけど。。。

実行環境

  • macOS Mojave 10.14.4
$ node -v
v10.15.3
$ npm -v
6.9.0

STEP0 : 作業用ディレクトリの作成

  • 作業用ディレクトリを作成
  • 作成したディレクトリに移動
  • node環境を初期化(package.jsonを作成)
$ mkdir sheets-node
$ cd sheets-node
$ npm init -y
$ ls
package.json

npm init -yは飛ばしても良いです。

STEP1 : GoogleSheetsAPIの有効化

以下のURLのENABLE THE GOOGLE SHEETS APIボタンを押下

01.png

DOWNLOAD CLIENT CONFIGURATIONボタンを押下、token.jsonを作業用ディレクトリに保存する。

02.png

STEP2 : クライアントライブラリのインストール

googleapisをインストール

$ npm install googleapis@39 --save
$ ls
node_modules      package.json      package-lock.json
credentials.json

STEP3 : サンプルの作成

index.jsを作成

$ vi index.js

以下からindex.jsをコピペ
https://developers.google.com/sheets/api/quickstart/nodejs#step_3_set_up_the_sample

index.js
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';

// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Google Sheets API.
  authorize(JSON.parse(content), listMajors);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getNewToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getNewToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error while trying to retrieve access token', err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

/**
 * Prints the names and majors of students in a sample spreadsheet:
 * @see https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
 * @param {google.auth.OAuth2} auth The authenticated Google OAuth client.
 */
function listMajors(auth) {
  const sheets = google.sheets({version: 'v4', auth});
  sheets.spreadsheets.values.get({
    spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
    range: 'Class Data!A2:E',
  }, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
    const rows = res.data.values;
    if (rows.length) {
      console.log('Name, Major:');
      // Print columns A and E, which correspond to indices 0 and 4.
      rows.map((row) => {
        console.log(`${row[0]}, ${row[4]}`);
      });
    } else {
      console.log('No data found.');
    }
  });
}

ファイル一覧

$ ls
credentials.json  node_modules      package.json
index.js          package-lock.json

STEP4 : サンプルを実行

nodeを実行。URLhttps://accounts.google.com/...が表示されると同時にコードを要求されるので、URLをブラウザにコピペしてアクセス。

node .でカレントディレクトリのindex.jsが実行される。

$ node .
Authorize this app by visiting this url: https://accounts.google.com/o/oauth2/v2/auth?xxxxx
Enter the code from that page here: 

ブラウザ上でアクセスを許可するGoogleアカウントを選択

Googleアカウントの登録状況により、選択画面が表示されないかもしれません。

03-1.png

許可を選択

03-2.png

許可を選択

04.png

画面に表示されるコードをコピー

05.png

先ほどのコンソールにコードを貼り付けてEnter

このタイミングで認証情報token.jsonが作成され、以降の認証はtoken.jsonを使って自動的に実行されます。

Enter the code from that page here: xxxxx
Token stored to token.json
Name, Major:
Alexandra, English
Andrew, Math
Anna, English
Becky, Art
Benjamin, English
Carl, Art
Carrie, English
Dorothy, Math
Dylan, Math
Edward, English
Ellen, Physics
Fiona, Art
John, Physics
Jonathan, Math
Joseph, English
Josephine, Math
Karen, English
Kevin, Physics
Lisa, Art
Mary, Physics
Maureen, Physics
Nick, Art
Olivia, Physics
Pamela, Math
Patrick, Art
Robert, English
Sean, Physics
Stacy, Math
Thomas, Art
Will, Math

サンプルコードindex.jsが実行され、Student Name列およびMajor列が一覧で表示されました。

5
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
12