Ruby 透過 Google API 串接 Excel (SpreadSheet)

本文章將一步一步教學如何透過 ruby 程式語言串接 google api ,對 google drive 的 SpreadSheet 進行存取。程式碼內容是以官方所提供的 API 為主,並且會附上相關參考資料。

MarsMars閱讀 2 分鐘
Ruby 透過 Google API 串接 Excel (SpreadSheet)

本文最後更新日期 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. 認證套件說明
Mars
關於作者Mars自由接案工程師 | Ruby on Rails

自由接案者、Ruby on Rails 工程師、水肺潛水員、業餘羽球、二胡、鋼琴愛好者。喜歡貓、狗。

延伸閱讀