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

本文最後更新日期 2024/1/17。
準備工作
- google API 憑證申請:參考 IT 邦幫忙 ,取得下載後的憑證 (json 檔案)
- 雲端檔案如果是 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
- cred_file 為準備工作所下載的憑證檔案
- scope 可參考官方資料 (搜尋 "AUTH_")
使用
client.get_spreadsheet_values(spreadsheet_id, "哈哈!A3:J507").to_h
- spreadsheet_id 為網址中的 https://docs.google.com/spreadsheets/d/{spreadsheet_id}/edit
- "哈哈!A3:J507" 可參考官方說明的範圍選擇方式
- 更多 client 的使用 API 可參考官方 ruby 文件
其他參考資料
- 認證失敗問題,顯示錯誤訊息: This operation is not supported for this document,參考 stackoverflow
- API 參數說明
- 認證套件說明
延伸閱讀
加入 BNI 商會心得
於 2023/10 加入了 BNI 台南商會(大信白金),本篇文章將分享加入後的心得,並持續更新心得內容,確認在不同階段的自己是否有偏離初衷。
rails app(web) 嵌入到 iframe 中
ruby on rails 的 web 預設是無法嵌入到 HTML iframe 中的,本篇文章將教學如何使其成功在不同網域中將 rails web 成功嵌入到 iframe 中。
設定電子郵件 DMARC
提供設定 DMARC 的範例,並且提供官方語法說明和檢測工具連結。

