LoginSignup
0
0

More than 1 year has passed since last update.

【Ruby on Rails】Googleスプレッドシートのデータをリストとして取得する方法

Last updated at Posted at 2023-02-09

前提条件

  • Ruby 3.1.0
  • Rails 7.0.4
  • 環境構築~GoogleAPI連携が完了していること(詳細は参考サイト参照)

やりたいこと

Googleスプレッドシートのデータをリストとして取得したい。

方法

1. データ取得するメソッドを作成する

Spreadsheet.rb
require 'googleauth'
require 'google/apis/sheets_v4'

module ABC
  class Spreadsheet
    SCOPE = [
      'https://www.googleapis.com/auth/drive',
      'https://www.googleapis.com/auth/spreadsheets'
    ]

    def initialize
      ・・・
      @service = Google::Apis::SheetsV4::SheetsService.new
    end

    # スプレッドシートIDとセルの範囲を引数にデータを取得する
    def get_values(spreadsheet_id, range)
      @service.get_spreadsheet_values(spreadsheet_id, range).values
    end
  end
end

2. 作成したメソッドを呼び出す

fetch_data.rb
def fetch_data
    # 作成したメソッドを呼び出して変数@dateに代入する
    @data = ABC::Spreadsheet.new.get_values('<スプレッドシートID>', '<テーブル名>!<取得するセルの範囲>')
end

※<取得するセルの範囲>には開始範囲と終了範囲の間に「:」を入れる
(例)A1セルからZ100セルの範囲で取得したい場合
A1:Z100

参考

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