LoginSignup
2
3

More than 1 year has passed since last update.

google スプレッドシートをAPIで操作する手順(ruby)

Last updated at Posted at 2021-01-12

これは何?

rubyを使ってgoogleスプレッドシートをAPIで操作するまでの手順です。

基本的に https://developers.google.com/sheets/api/quickstart/ruby をやっているだけなので英語の説明でも問題ない方は公式の方を見てください。

対象者

rubyの実行環境が自分で作れる人、または既に存在する人が対象です。

手順

https://developers.google.com/sheets/api/quickstart/ruby
の[Enable the Google Sheets API]ボタンをクリックします。

01.jpg

次の画面でProject名を入力します。
[Quickstart]のままでも問題ないので入力したら[NEXT]をクリックします。
02.jpg

次の画面では作成するOAuth clientを選びます。
[Desktop app]を選択して[CREATE]ボタンをクリックします。
03.jpg

次の画面では[DOWNLOAD CLIENT CONFIGURATION]ボタンが表示されるのでクリックして credentials.jsonファイルをダウンロードします。
04.jpg

続いてrubyのプログラムを作成していきます。
まずプログラムを格納するためのディレクトリを作成していきます。
今回は「sample_google_spreadsheet_api」ディレクトリを作成しました。(ディレクトリ名はなんでも大丈夫です)

cd ~
mkdir sample_google_spreadsheet_api

続いてgemのinstallを行います。
05.jpg

GoogleのQuickstartページでは上記のように記載していますが、今回はGemfileを作成していきます。

cd sample_google_spreadsheet_api
bundle init

Gemfileが作成されるので以下のように編集します。

Gemfile
# frozen_string_literal: true

source "https://rubygems.org"

git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }

--- # gem "rails"
+++ gem 'google-api-client'

bundle installします。

bundle config --local path 'vendor/bundle'
bundle install

ダウンロードしたcredentials.json を以下へ配置します。

# fileディレクトリを作成してcredentials.jsonを格納
mkdir file

sample_google_spreadsheet_api/file/credentials.json

続いてsheets/quickstart/quickstart.rb を作成します。

mkdir sheets
cd sheets
mkdir quickstart
cd quickstart
touch quickstart.rb 

quickstart.rb へ以下のプログラムを記載します。

これはGoogleのQuickstartへ記載されているものです。

require "bundler/setup"
require "google/apis/sheets_v4"
require "googleauth"
require "googleauth/stores/file_token_store"
require "fileutils"
OOB_URI = "urn:ietf:wg:oauth:2.0:oob".freeze
APPLICATION_NAME = "Google Sheets API Ruby Quickstart".freeze
CREDENTIALS_PATH = "./file/credentials.json".freeze
# The file token.yaml stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
TOKEN_PATH = "token.yaml".freeze
SCOPE = Google::Apis::SheetsV4::AUTH_SPREADSHEETS_READONLY
##
# Ensure valid credentials, either by restoring from the saved credentials
# files or intitiating an OAuth2 authorization. If authorization is required,
# the user's default browser will be launched to approve the request.
#
# @return [Google::Auth::UserRefreshCredentials] OAuth2 credentials
def authorize
  client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH
  token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH
  authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store
  user_id = "default"
  credentials = authorizer.get_credentials user_id
  if credentials.nil?
    url = authorizer.get_authorization_url base_url: OOB_URI
    puts "Open the following URL in the browser and enter the " \
             "resulting code after authorization:\n" + url
    code = gets
        credentials = authorizer.get_and_store_credentials_from_code(
            user_id: user_id, code: code, base_url: OOB_URI
        )
    end
    credentials
end

# Initialize the API
service = Google::Apis::SheetsV4::SheetsService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize

# Prints the names and majors of students in a sample spreadsheet:
# https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
spreadsheet_id = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms"
range = "Class Data!A2:E"
response = service.get_spreadsheet_values spreadsheet_id, range
puts "Name, Major:"
puts "No data found." if response.values.empty?
response.values.each do |row|
    # Print columns A and E, which correspond to indices 0 and 4.
    puts "#{row[0]}, #{row[4]}"
end

内容としては
credentials.jsonをもとに認可コードを取得して認可コードからアクセストークンを取得し
https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
の内容をコマンドラインへ出力するというものです。
以下が実行コマンドです。

ruby sheets/quickstart/quickstart.rb

実行結果


> ruby sheets/quickstart/quickstart.rb

Open the following URL in the browser and enter the resulting code after authorization:
https://accounts.google.com/o/oauth2/auth?access_type=offline&approval_prompt=force&client_id=[client_id]&include_granted_scopes=true&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&scope=https://www.googleapis.com/auth/spreadsheets.readonly

初回実行時はURLが表示されるのでそれにアクセスします。

1: google アカウントを選択します。
06.jpg

2:認可画面が表示されるので「許可」クリックします。
07.jpg

3: 認可コードが表示されるので実行画面へ貼り付けReturn
08.jpg

実行結果へ貼り付けてReturn

> ruby sheets/quickstart/quickstart.rb 

Open the following URL in the browser and enter the resulting code after authorization:
https://accounts.google.com/o/oauth2/auth?access_type=offline&approval_prompt=force&client_id=[client_id]&include_granted_scopes=true&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&scope=https://www.googleapis.com/auth/spreadsheets.readonly
# ↓へ上記で取得した認可コードを貼り付けReturn
[認可コード]

# GoogleSpreadSheetから取得した結果が表示されます。
Name, Major:
Alexandra, English
Andrew, Math
Anna, English
Becky, Art
Benjamin, English
Carl, Art
Carrie, English
Dorothy, Math
Dylan, Math
Edward, English
Ellen, Physics
Fiona, Art
John, Physics
Jonathan, Math
Joseph, English
Josephine, Math
Karen, English
Kevin, Physics
Lisa, Art
Mary, Physics
Maureen, Physics
Nick, Art
Olivia, Physics
Pamela, Math
Patrick, Art
Robert, English
Sean, Physics
Stacy, Math
Thomas, Art
Will, Math

サンプルのGoogleスプレッドシートの内容が表示されれば成功です。

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