本文最後更新日期 2024/1/17。

準備工作

  1. google API 憑證申請:參考 IT 邦幫忙 ,取得下載後的憑證 (json 檔案)
  2. 雲端檔案如果是 xlsx 的話,必須先轉換為 google 試算表格式。 (參考以下截圖)

環境

# Gemfile
gem 'googleauth'
gem 'google-apis-sheets_v4'

讀取憑證

client = Google::Apis::SheetsV4::SheetsService.new
cred_file = '/tmp/secret.json'
authorizer = Google::Auth::ServiceAccountCredentials.make_creds(json_key_io: File.open(cred_file), scope: [Google::Apis::SheetsV4::AUTH_SPREADSHEETS])
client.authorization = authorizer

  1. cred_file 為準備工作所下載的憑證檔案
  2. scope 可參考官方資料 (搜尋 "AUTH_")

使用

client.get_spreadsheet_values(spreadsheet_id, "哈哈!A3:J507").to_h

  1. spreadsheet_id 為網址中的  https://docs.google.com/spreadsheets/d/{spreadsheet_id}/edit 
  2. "哈哈!A3:J507" 可參考官方說明的範圍選擇方式
  3. 更多 client 的使用 API 可參考官方 ruby 文件

其他參考資料

  1. 認證失敗問題,顯示錯誤訊息: This operation is not supported for this document,參考 stackoverflow
  2. API 參數說明
  3. 認證套件說明