donfanning
8/15/2018 - 1:45 PM

Use Google Sheets API and Service Account to import Data to Rails APP

Use Google Sheets API and Service Account to import Data to Rails APP

require 'google/apis/sheets_v4'
require 'googleauth'

class GoogleSheetCrawler
  def self.get_sheet_array_from_google_sheet(options = {})
    service = Google::Apis::SheetsV4::SheetsService.new
    service.authorization = get_google_auth
    service.get_spreadsheet_values(
      "a_sheet_id_you_can_fine_on_google_sheet_url",
      "SHEETNAME!A2:M2000"
    ).values
  end

  private

  def self.get_google_auth
    scope = [Google::Apis::SheetsV4::AUTH_SPREADSHEETS_READONLY]
    file = File.open("YOUR_FILE_PATH_OF_SECRET_JSON_FILE", 'r')
    authorization = Google::Auth::ServiceAccountCredentials.make_creds({:json_key_io=> file, :scope => scope})
  end
end
# Gemfile

gem 'google-api-client'
gem 'googleauth'