0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyでspreadsheetを扱えるようになろう!

0
Posted at

概要

インターンの仕事の中でRubyを使ってスプレッドシートに取得したデータを書き出すというものがあったので、その一連をアウトプットしようと思いこの記事を書くに至りました。

環境

macOS 10.15.7
Ruby 2.5.3

RubyとGoogleDriveの接続と準備

以下では下記のページを参考にしています。
幾分か内容が重複している部分がありますが予めご了承ください。

RubyでGoogle スプレッドシートを操作する

①今回は、Rubyのgoogle_driveというgemを使います
ですので、Gemfileを用意してgoogle_driveのgemを取り込んでください。

②下記のGoogle Cloud plattoformのAPIライブラリからGoogle Drive APIとGoogle Sheets APIを有効にしてください
Google API ライブラリ

③Google APIの認証情報(client IDとclient Secret)を取得します
基本的にはAPIキーでもなんでも良いですが、僕はOAuthクライアントIDを使っています。
OAutを選択すると、Rubyのspreadsheet系の記事でアプリケーションの種類で「その他」を選択しているものが多いですが、2021年現在、「その他」を選択することができませんので、RailsなどでWEBアプリなどを作る場合以外は、「デスクトップアプリ」を選択するといいでしょう。

④同ディレクトリ内にconfig.jsonというファイルを作成し、③で発行されたclient IDとclient secretを下記のように記入してください

config.json
{
  "client_id": "xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
  "client_secret": "xxxxxxxxxxxxxxxxxxxxxxxx"
}

⑤実際にspreadsheetを操作するRubyファイルを用意。ここでは、サンプルという意味を込めてsample.rbとしておきます。

⑥Rubyから操作したいspreadsheetを新たに作成する
https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxxxxxxxxxxxxxxx/のようにspeadsheetのURLからkeyを取得する
(keyはxxxxxxxxxxxxxxxxxxxxxxxxxxxの部分に該当する)

⑦sample.rbを下記のように編集

sample.rb
require 'google_drive'

session = GoogleDrive::Session.from_config("config.json")
sheet = session.spreadsheet_by_key("xxxxxxxxxxxxxxxxxxxxxxxxxxx").worksheet_by_title("#{作成したspreadsheetのtitle}")

⑧⑦のファイルを実行する
その際に、Open this page: https://accounts.google.com/xxx
と表示されるので、出力されたURLをブラウザで開き、表示された文字列を選択してターミナルに貼り付けます。
これで初回の認証が完了するので、以降は自由にスプレッドシートを操作することが可能です。
※この認証が完了すると先ほど作成したjsonファイルが自動で更新されます

まとめ

spreadsheetの遠隔操作はかなり需要のあるスキルだと思いますし、他のGoogle APIを利用する良い練習になるとおもいますので、ぜひ利用してみてください。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?