close

(圖片來源)

在使用 Google Sheet API 之前必須先啟用該服務,如何啟用可以參考 [Google] create google api project

 

Step1. 安裝套件

python 串接 Google Sheet API 其實沒有想像中那麼困難,其實已經有人寫好相關的套件了,我們只需要下載安裝套件並 import 它就可以了!

pip install --upgrade google-api-python-client

 

Step2. 輸入下方程式碼

主要分為 3 部份,也就是黃色行數的位置:
1. getCredentials function:取得使用者的授權並儲存授權資料
2. getSheetValue function:取得 Google 表單中的資料,需要的參數有表單 ID截取資料範圍
3. __name__ == ‘__main__’:程式執行區

# encoding: utf-8
from __future__ import print_function
import httplib2
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

"""
取得授權
    Gets valid user credentials from storage.
    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.
    Returns:
        Credentials, the obtained credential.
"""
def getCredentials():

    SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
    CLIENT_SECRET_FILE = 'client_secret.json'
    APPLICATION_NAME = 'Google Sheets API Python Quickstart'

    try:
        import argparse
        flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
    except ImportError:
        flags = None

    # 授權目錄
    credential_dir = '.credentials'

    # 取得授權紀錄
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir, 'sheets.googleapis.com-python-quickstart.json')
    store = Storage(credential_path)
    credentials = store.get()

    # 判斷是否有授權紀錄或是受全是否失效,若沒有或失效則重新或取授權並儲存授權
    if not credentials or credentials.invalid:
        clientsecret_path = os.path.join(credential_dir, CLIENT_SECRET_FILE)
        flow = client.flow_from_clientsecrets(clientsecret_path, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

"""
取得 Sheet 資料
    Shows basic usage of the Sheets API.

    Creates a Sheets API service object and prints the names and majors of
    students in a sample spreadsheet:
    https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
"""
def getSheetValue(spreadsheetId, rangeName):

    # 建立 Google Sheet API 連線
    credentials = getCredentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                    'version=v4')
    service = discovery.build('sheets', 'v4', http=http, discoveryServiceUrl=discoveryUrl)

    # 取的 Sheet 資料
    result = service.spreadsheets().values().get(spreadsheetId=spreadsheetId, range=rangeName).execute()
    values = result.get('values', [])

    return values


if __name__ == '__main__':
    spreadsheetId = '11p7U3IN7QioeyzuRU0_EoOcMvSFTbnFRsO2q5Oizwb0'
    rangeName = 'sheet1!A1:E'
    values = getSheetValue(spreadsheetId, rangeName)

    if not values:
        print('No data found.')
    else:
        for row in values:
            # Print columns A and E, which correspond to indices 0 to 4.
            print('%s, %s, %s, %s, %s' % (row[0], row[1], row[2], row[3], row[4]))

 

※ 注意事項
(1) 必須先下載憑證,並存放至 .credentials 目錄中

 

(2) 必須取得表單 ID 與 要取得範圍,並設定在變數中

表單 ID 藏在 URL 中,則 spreadsheetId 的變數就是設定 “11p7U3IN7QioeyzuRU0_EoOcMvSFTbnFRsO2q5Oizwb0″

 

要取得表單資料範圍需要注意 2 個地方,也就是頁籤名稱欄位範圍,依照此次範例 rangeName 變數的值為“sheet1!A1:E",你可能會發現為什麼是寫 A1 而不是 A ,其實 A 也是可以的,只是要在這邊提醒限制行數的使用方式!

 

Step3. 執行程式

python GoogleSheetAPI.py

執行結果如下:

 

執行完第一次你會發現在你的授權目錄下會多一個 sheets.googleapis.com-python-quickstart.json 檔案,這是因為 getCredentials 把取得的授權內容儲存至該檔案中,這麼做的用意是,不需要每次執行程式的時候都要取得使用者的授權,當然該授權若失效還是會需要重新取得使用者授權才可以繼續執行哦!

 

參考:

Python Quickstart
Reading & Writing Cell Values
Basic Reading
Google Spreadsheets and Python

 

 

arrow
arrow

    Mayuge 發表在 痞客邦 留言(1) 人氣()