LoginSignup
7
5

More than 1 year has passed since last update.

Node.jsでGoogleスプレッドシートを使用する方法

Last updated at Posted at 2022-01-01

1.Googleプロジェクトを作成し、APIを有効にして、資格情報を追加する

GoogleアカウントでGoogle APIコンソールにアクセスし、「新しいプロジェクト」からプロジェクトを作成する

5076c797591c879a3d89b5a63532ad98.png

プロジェクト名を入力して、作成。(場所は組織なしでOK)
07d4607c4158213b077da2235ced94c3.png

[APIとサービス]からAPIとサービスの有効化を選択
37f1217c04731689859c9afa23be3a0a.png

「Google Drive API」と「Google Sheets API」を有効化する
6f1ec3369b7816c2170ab7dc630f373d.png
366f24b047af275a5d7770ca7871a115.png

認証情報を作成する
59f7a7b6dccb4c0edcf67eacba54c5ba.png

入力例
API: Google Drive API
アクセスするデータの種類: アプリケーションデータ
〜でこのAPIを使用する予定はありますか?: いいえ、使用していません

6e30959f6d80ea3fa8f7299950493e1b.png

サービスアカウント名を入力
8c2d8d434cad75d077d0465c86cfbde2 (1).png

ロールを選択
基本-->編集者
7bc7ab6d325b4798971cb9bf8915618a.png

鍵を追加--->新規作成
81ac787d17519d5c41c8ee351573d8a7.png

JSON形式で作成
4e590bc1f5758667a6fc42f017f6ad81.png

スプレッドシートでサービスアカウント(ダウンロードされたJSONのclient_email)を共有する。

準備完了!

2.作成(Create)、取得(Retrieve)、更新(Update)、削除(Delete)[CRUD]

スプレッドシートを使用したいディレクトリ上で下記コマンドを実行しパッケージをインストール

npm i google-spreadsheet

下記サンプルコード

sample.js
(async function() {
    const {
        GoogleSpreadsheet
    } = require('google-spreadsheet');
    const creds = require('./client_secret.json'); // ダウンロードしたJSON
    const doc = new GoogleSpreadsheet('*spreadsheet ID*');

    doc.useServiceAccountAuth(creds);

    await doc.loadInfo(); 
    console.log(doc.title);
    const sheet = doc.sheetsByIndex[0];doc.sheetsByTitle[title]

    const rows = await sheet.getRows();
    console.log(rows.length);
}());

sample.jsの実行結果
5f62dedf7704a5fc7c56f4fcd79a14e3.png

今回使用したスプレッドシート↓
862a19ac512e17d2326ff071595684bc.png

成功!

 参考

7
5
1

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
7
5