19
25

More than 5 years have passed since last update.

Google Sheets APIを使って限定公開のシートをJavascriptで操作する

Last updated at Posted at 2017-06-08

はじめに

Google Sheets APIって便利ですよね。簡易なアプリケーションならばDBの代わりに使ったりもできます。
限定公開のシートにアクセスし読み込み書き込みを行っていきます。

ちなみに限定公開な必要がない場合はwebに公開して下記を参考にサクッとアクセスすることも可能です。
https://developers.google.com/sheets/api/quickstart/js

プラグイン

Javascriptのクライアントを読み込む
https://developers.google.com/api-client-library/

Google APIコンソールからプロジェクトの作成、Sheets API のアプリケーションの登録をして
クライアントIDを取得しておきましょう。
https://console.developers.google.com/start/api?id=sheets.googleapis.com

サンプル

(サンプルはES6で記述されております)

Setup

ライブラリの読み込みは以下

//- bodyの最後の方に追加
script(src='https://apis.google.com/js/api.js')

クライアントのイニシャライズ

gapi.load('client:auth2', ()=> {
  gapi.client.init({
    clientId: '<YOUR CLIENT ID>',
    scope: 'https://www.googleapis.com/auth/spreadsheets',
    discoveryDocs: ['https://sheets.googleapis.com/$discovery/rest?version=v4']
  })
});

Auth

限定公開のシートにアクセスするために権限を持っているユーザーに認証をさせます。
signIn のメソッドを呼び出した時にログイン用のダイアログが開きます。

const auth = gapi.auth2.getAuthInstance();
auth.signIn();

シートデータの取得/書き込み

values.getはPromiseを返します。引数として取得した結果の参照が可能

gapi.client.sheets.spreadsheets.values.get({
  spreadsheetId: '<YOUR SheetID>',
  range: '<YOUR Sheet Name>!A2:E' // rangeの指定
}).then((res)=>{
  // value is res.result.values
});

書き込みや上書きは下記を参考に(API Explorerが非常に便利)
https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update

参考

JavaScript Quickstart
https://developers.google.com/sheets/api/quickstart/js

19
25
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
19
25