Skip to content

Instantly share code, notes, and snippets.

@ctosib
Created December 20, 2016 09:27
Show Gist options
  • Save ctosib/90d168e0d34556f4cf0142181f9c88c6 to your computer and use it in GitHub Desktop.
Save ctosib/90d168e0d34556f4cf0142181f9c88c6 to your computer and use it in GitHub Desktop.
讀取Google Sheet via google API
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
from apiclient.discovery import build
"""
Reference:
1.Google OAuth 2.0 for Service Account
2..OAuth 2.0 API scope:https://developers.google.com/identity/protocols/googlescopes#sheetsv4
3..Install python api library:https://developers.google.com/api-client-library/python/start/installation
4..Google Sheet api:https://developers.google.com/resources/api-libraries/documentation/sheets/v4/python/latest/index.html
5.Google Sheet api for python:Quickstart:https://developers.google.com/sheets/api/quickstart/python
"""
scopes = ['https://www.googleapis.com/auth/spreadsheets']
#利用建立service account所下載的json檔進行驗證。
#key.json是建立完Service Account之後所下載的檔案
credentials = ServiceAccountCredentials.from_json_keyfile_name('key.json', scopes=scopes)
http_auth = credentials.authorize(Http())
#API名稱及版本可參考下列網址。
#https://developers.google.com/api-client-library/python/apis/
sheettest = build('sheets', 'v4', http=http_auth)
result = sheettest.spreadsheets().values().get(spreadsheetId={spreadsheetsID},range="Sheet1!B2:B").execute()
for i in result['values']:
print i[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment