
使用 Python 將資料寫入 Google 試算表
今天來介紹,如何使用 Python 連線到 Google 試算表,並將資料寫入進去。
要和 Google Sheets 連線,必須要使用到 gspread 和 oauth2client 套件,還有 Google Sheets API。
以下請跟著教學一步一步實作!
使用到的工具:
Python 版本:3.8.5
gspread 版本:3.7.0
oauth2client 版本:4.1.3
一、申請 Google Sheets API
1. 請輸入以下網址,登入 Google 的帳號後進入首頁。
https://console.developers.google.com

2. 輸入專案的名稱及 ID

3. 點選上方的「啟用 API 和服務」

4. 於搜尋框輸入「Google Sheets API」

點選啟用

5. 啟用之後,點選於畫面左方,最底下的「憑證」,然後於右上方點選「建立憑證」。

選擇第二個「服務帳戶」

6. 輸入帳戶的詳細資料

二和三不用填,直接完成即可。

7. 完成後,底下服務帳戶多了一個電子郵件地址。

8. 請點選那個電子郵件地址,進入詳細資料頁面。
進入後於左方點選「服務帳戶」

請先將電子郵件地址複製到記事本,等等試算表要共用時,要將此地址輸入。
9. 點選上方的「金鑰」,選擇「建立新的金鑰」。

10. 選擇 JSON 後按建立

這個金鑰先存放在隨便一個資料夾,等等在建立 Python 檔案的時候,要放在同一個資料夾。
二、建立試算表並設定共用
1. 建立一個新的試算表

2. 點選右上角的「共用」,把剛剛紀錄的電子郵件輸入。

選為編輯者,傳送

三、安裝套件和撰寫程式碼
1. 開啟 Anaconda Prompt,輸入以下指令安裝套件:
pip install gspread oauth2client

2. 將 Google 試算表 網址的代碼複製到記事本

3. 開啟 Spyder (或妳慣用的文字編輯器),建立一個新的 Python 檔案,並輸入以下程式碼:
import gspread
from oauth2client.service_account import ServiceAccountCredentials as SAC

4. 設定 json 檔案路徑及程式操作範圍
Json = 'inbound-sight-311513-47edd249188c.json' # Json 的單引號內容請改成妳剛剛下載的那個金鑰
Url = ['https://spreadsheets.google.com/feeds']

5. 接著撰寫連線至資料表的 Code
Connect = SAC.from_json_keyfile_name(Json, Url)
GoogleSheets = gspread.authorize(Connect)

ServiceAccountCredentials(因為太長所以直接取名成 SAC) 的 from_json_keyfile_name 方法,帶入兩個參數後給變數 Connect,再透過 gspread 套件的 authorize 方法,帶入參數 Connect,連線至資料庫。
6. 開啟資料表及工作表
Sheet = GoogleSheets.open_by_key('14hYfea45xVlp5eczXouYT-r54iUndGyCPBS9TD_rJyU') # 這裡請輸入妳自己的試算表代號
Sheets = Sheet.sheet1

7. 寫入資料至 Google Sheets
dataTitle = ["會員 ID", "使用暱稱", "密碼"]
datas = ["Captain", "Picard", "5678"]
Sheets.append_row(dataTitle)
Sheets.append_row(datas)
print("寫入成功")

先設定好串列,再使用 append_row 方法,將資料寫入至 Google Sheets。
8. 使用 get_all_values() 方法,看能不能從 試算表 讀取到資料
print(Sheets.get_all_values())

有讀取到就是寫入和讀取都有成功

Google Sheets 也有資料進去了!

Python 完整程式碼:
# 匯入模組
import gspread
from oauth2client.service_account import ServiceAccountCredentials as SAC
# 設定 json 檔案路徑及程式操作範圍
Json = 'inbound-sight-311513-47edd249188c.json'
Url = ['https://spreadsheets.google.com/feeds']
# 連線至資料表
Connect = SAC.from_json_keyfile_name(Json, Url)
GoogleSheets = gspread.authorize(Connect)
# 開啟資料表及工作表
Sheet = GoogleSheets.open_by_key('14hYfea45xVlp5eczXouYT-r54iUndGyCPBS9TD_rJyU')
Sheets = Sheet.sheet1
# 寫入資料
dataTitle = ["會員 ID", "使用暱稱", "密碼"]
datas = ["Captain", "Picard", "5678"]
Sheets.append_row(dataTitle)
Sheets.append_row(datas)
print("寫入成功")
# 讀取資料
print(Sheets.get_all_values())
Python 執行範例:
如果覺得文章內容還不錯的話,麻煩請幫我點個讚!感謝
可以多點幾次喔~~
第一次點讚需使用 Google 或 Facebook 帳號註冊

