railsがんばる子

Ruby on Railsがんばる子です。胡蝶蘭のECサイトを運営しています。

rubyからGoogleDriveのスプレッドシートに書き込む

準備1

Gyazo - c274baa73bafb81335bccf1d79ff141a.png

Gemfile

gem install 'google_drive'

セッションを作る

client = Google::APIClient.new
auth = client.authorization
auth.client_id = 'クライアントID'
auth.client_secret = 'クライアントシークレット'
auth.scope =
'https://www.googleapis.com/auth/drive ' +
'https://spreadsheets.google.com/feeds/'
auth.redirect_uri = 'リダイレクトURI'

puts('1. Open this page:\n%s\n\n' % auth.authorization_uri)
puts('2. Enter the authorization code shown in the page: ')
auth.code = $stdin.gets.chomp
auth.fetch_access_token!

session = GoogleDrive.login_with_oauth(auth.access_token)

これを実行すると、URIにアクセスしてauthorization codeを入れてくれと言われるので言う通りにする。

Gyazo - 9c26f5fb2df5f9f67456f92c658ba312.png

これで、sessionが出来ます。

毎回やるのはしんどいので、refresh_tokenを利用します。 refresh_tokenはauthが終わった後、auth.refresh_tokenにて取り出すことができます。

client = Google::APIClient.new
auth = client.authorization
auth.client_id = 'クライアントID'
auth.client_secret = 'クライアントシークレット'
auth.scope =
'https://www.googleapis.com/auth/drive ' +
'https://spreadsheets.google.com/feeds/'
auth.redirect_uri = 'リダイレクトURI'
auth.refresh_token = 'リフレッシュトークン' #前回接続した時にauth.refresh_tokenを利用して取り出した値を控えておくこと
# 環境変数や.envに設定されることをおすすめします

begin
  auth.fetch_access_token!
rescue Signet::AuthorizationError
  puts('1. Open this page:\n%s\n\n' % auth.authorization_uri)
  puts('2. Enter the authorization code shown in the page: ')
  auth.code = $stdin.gets.chomp
  auth.fetch_access_token!
end

session = GoogleDrive.login_with_oauth(auth.access_token)

スプレッドシートをコピーする

ここまできたら後は簡単、3分クッキングです。

original_file = session.spreadsheet_by_key('ファイルID')
destination_file = original_file.copy('新しいファイルのタイトル')

コピーしたいもとのファイルIDはURIに表現されています。

https://docs.google.com/spreadsheets/d/1-frxrc1H7_-6LPcNANRR5Wxdz05VPPEZuD79jmRDIUw/edit#gid=0

セルに書き込む

シートを取得して、入力したあと保存するという手順です。

sheet = destination_file.worksheet_by_title('シート名称')
sheet['A1'] = '何か'
sheet.save

以上。