2
4

More than 3 years have passed since last update.

Rails(Ruby)アプリからスプレッドシートに書き込み

Last updated at Posted at 2020-01-15

GCP側のでやること

GCPのコンソール(https://cloud.google.com)から、
・「Google Drive API」と「Google Sheets API」を有効化
スクリーンショット 2020-01-15 15.49.43.png
スクリーンショット 2020-01-15 15.48.27.png

・OAuth Client ID取得
スクリーンショット 2020-01-15 15.50.54.png

注意:WEBとかiOSとかではなく、「Other」を選ぶ

Rails(Ruby)側

gemを追加

Gemfile
gem 'google_drive'

認証情報を記載するconfig.jsonを作成

touch config.json
config.json
{
  "client_id": "xxxxxxx-xxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
  "client_secret": "xxxxxxxXXxxxxxxxxxxxxxxxxx"
}

キーからスプレッドシートを取得。スプレッドシートのURLのうち、https://docs.google.com/spreadsheets/d/xxxこのxxxの部分がスプレッドシートのキーになる。

require "google_drive"

session = GoogleDrive::Session.from_config("config.json")
sheet = session.spreadsheet_by_key("xxxxxxxxxxxxxxxxxxxxxxxxxxx").worksheets[0]

# 書き込み
sheet[1,1] = "From API"
sheet.save

実行すると、認証が始まるので表示されるURLに対象アカウントでログインして認証。

書き込まれるかどうか確認

スクリーンショット 2020-01-15 16.12.15.png

2
4
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
2
4