Created
February 3, 2019 08:24
-
-
Save KentaKudo/0acdee2876b693d110a1713e122a5353 to your computer and use it in GitHub Desktop.
A sample code to access Google Sheet in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# See: https://developers.google.com/sheets/api/quickstart/python | |
import pickle | |
import os.path | |
from googleapiclient.discovery import build | |
from google_auth_oauthlib.flow import InstalledAppFlow | |
from google.auth.transport.requests import Request | |
SCOPES = ['https://www.googleapis.com/auth/spreadsheets'] # read/write access | |
SHEET_ID = '<sheet_id>' | |
RANGE_NAME = 'original!A1:A1' | |
def main(): | |
creds = auth() | |
values = get_values(creds) | |
if not values: | |
print('No data found.') | |
else: | |
for row in values: | |
print('%s' % row[0]) | |
def auth(): | |
creds = None | |
if os.path.exists('token.pickle'): | |
with open('token.pickle', 'rb') as token: | |
creds = pickle.load(token) | |
if not creds or not creds.valid: | |
if creds and creds.expired and creds.refresh_token: | |
creds.refresh(Request()) | |
else: | |
flow = InstalledAppFlow.from_client_secrets_file( | |
'credentials.json', SCOPES) | |
creds = flow.run_local_server() | |
with open('token.pickle', 'wb') as token: | |
pickle.dump(creds, token) | |
return creds | |
def get_values(creds): | |
service = build('sheets', 'v4', credentials=creds) | |
# Call the Sheets API | |
sheet = service.spreadsheets() | |
result = sheet.values().get(spreadsheetId=SHEET_ID, range=RANGE_NAME).execute() | |
return result.get('values', []) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment