LoginSignup
9
6

More than 1 year has passed since last update.

Node.jsでGoogle Spread Sheetsを読み取る 【Sheet API v4】

Last updated at Posted at 2021-05-03

Google Sheet API v4版です。手順など定期的にアップデートしてますが、改めてまとめてみました。

過去記事: Node.jsでGoogle SpreadSheetsを操作してみよう。【GAS不使用】

async/awaitで書いたり、モジュールも使ったりだいぶシンプルに出来るようになってきました。

GAS不要なのでNode.jsでやりたい人向けですね。

環境

手順

作業フォルダ&利用モジュール準備

$ mkdir sheet
$ cd sheet
$ npm init -y
$ npm i googleapis google-auth-token-generator

credentialsファイルを作成

公式のNode.js quickstartを見てcredentials.jsonをDLしましょう。

アプリケーション種類はデスクトップアプリにします。

スクリーンショット 2021-05-04 0.24.17.png

client_secret.jsonclient_secret_xxxxxxx.jsonといった名前の場合もありますが、credentials.jsonにリネームします。

また、先ほど作成したsheetフォルダにcredentials.jsonを設置します。

tokenの生成

パーミッションを選択してtokenを作成します。

$ npx google-auth-token-generator

今回は既存のシートの読み取りだけしたいので、パーミッション選択ではspreadsheets.readonlyを選択します。

スクリーンショット 2021-05-04 0.20.09.png

認証など進めるとtoken.jsonが生成されます。

Sheet APIでスプレッドシートの値を見る

サンプルコードが以下です。

'use strict';

const {google} = require('googleapis');
const {oAuth2ClientGen} = require('google-auth-token-generator');

(async () => {
    const auth = oAuth2ClientGen({library: google});
    const sheets = google.sheets({version: 'v4', auth});

    try {
        const res = await sheets.spreadsheets.values.get({
            spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
            range: 'Class Data!A2:E',
        });

        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.');
        }

    } catch (error) {
        console.log('The API returned an error: ' + error);
    }
})();

実行

$ node app.js 
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

実態は公式チュートリアルにもあるこちらのシートの内容を読み込んでます。

https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit?usp=sharing

よもやま

google-auth-token-generatorは自作モジュールなので公式の手順と若干異なりますが、YoutubeやGmailなどGoogle系のAPIで同じ処理を書くのが辛いのでnpmパッケージ化してみました。

今回cliツールだけじゃなくてrequireできるモジュールとしてもアップデートさせてみましたが個人的にはめちゃ便利です。

9
6
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
9
6