Ruby で Google スプレッドシートを操作する方法をまとめてみました。
事前準備
Google API Console(APIライブラリ) から Google Drive API と Google Sheets API を有効化します。
手順
- Google Cloud consoleから API ライブラリにアクセスし
- 「新しいプロジェクト」から新規プロジェクトを作成
- 作成したプロジェクトを選択し、「Google Drive API」と「Google Sheets API」を有効化
- 「APIとサービス」> 「認証情報」へと移動
- 「認証情報を作成」>「OAuth クライアント ID」を選択
- その後に表示される同意画面で必要事項を入力
- 「アプリケーションの種類」から「その他」を選択して作成
- クライアントIDとクライアントシークレットが発行
google-drive-ruby
Rubyとスプレッドシートの連携には google-drive-ruby を使います。
github.com
インストール
Gemfileを用意して 「bundle install --path vendor/bundle」を実行します。
source 'https://rubygems.org' gem 'google_drive'
認証
Google API Console で作成したクライアントIDとクライアントシークレットから、以下のような json ファイルを作成します。
(以下のような内容の config.json というファイルを作成)
{ "client_id": "xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com", "client_secret": "xxxxxxxxxxxxxxxxxxxxxxxx" }
json ファイルと同じディレクトリに以下のようなコードを作成します。
require "google_drive" # https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxxxxxxxxxxxxxxx/ sheet_key = "事前に書き込みたいスプレッドシートを作成し、上記スプレッドシートのURL(「xxx」の部分)を以下のように指定" session = GoogleDrive::Session.from_config("config.json") sheets = session.spreadsheet_by_key(sheet_key)
操作
新規スプレッドシート作成
新規スプレッドシートを作成するコードです。
require "google_drive" session = GoogleDrive::Session.from_config("config.json") # マイドライブ内に作成される session.create_spreadsheet("{{スプレッドシート名}}")
新規ワークシート作成
新規ワークシートを作成するコードです。
require "google_drive" session = GoogleDrive::Session.from_config("config.json") sheets = session.spreadsheet_by_key("xxxxxxxxxxxxxxxxxxxxxxxxxxx") # 既存のスプレッドシートに新規シート(ワークシート)を追加 sheets.add_worksheet("シート名")
ワークシート書き込み
ワークシートに書き込みを行うコードです。
require "google_drive" session = GoogleDrive::Session.from_config("config.json") # 処理対象のスプレッドシートを指定 sheets = session.spreadsheet_by_key("xxxxxxxxxxxxxxxxxxxxxxxxxxx").worksheet_by_title("シート名") # A1セルに「hello world」と書き込む # [行番号, 列番号]で指定することが可能 sheets[1,1] = "hello world!!"
ワークシート情報取得
ワークシートの情報を取得するコードです。
require "google_drive" session = GoogleDrive::Session.from_config("config.json") # 処理対象のスプレッドシートを指定 sheets = session.spreadsheet_by_key("xxxxxxxxxxxxxxxxxxxxxxxxxxx").worksheet_by_title("シート名") spsheet.worksheets.each do |ws| print (ws.gid) print (ws.title) print (ws.rows.map{|ary| ary.join("\t")}.join("\n")) end