doyu commited on
Commit
02934e6
1 Parent(s): f100e2f

copy quickstart.py

Browse files

https://developers.google.com/sheets/api/quickstart/python
https://github.com/googleworkspace/python-samples/tree/main/sheets/quickstart

Files changed (1) hide show
  1. quickstart.py +63 -0
quickstart.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import print_function
2
+
3
+ import os.path
4
+
5
+ from google.auth.transport.requests import Request
6
+ from google.oauth2.credentials import Credentials
7
+ from google_auth_oauthlib.flow import InstalledAppFlow
8
+ from googleapiclient.discovery import build
9
+ from googleapiclient.errors import HttpError
10
+
11
+ # If modifying these scopes, delete the file token.json.
12
+ SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
13
+
14
+ # The ID and range of a sample spreadsheet.
15
+ SAMPLE_SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
16
+ SAMPLE_RANGE_NAME = 'Class Data!A2:E'
17
+
18
+
19
+ def main():
20
+ """Shows basic usage of the Sheets API.
21
+ Prints values from a sample spreadsheet.
22
+ """
23
+ creds = None
24
+ # The file token.json stores the user's access and refresh tokens, and is
25
+ # created automatically when the authorization flow completes for the first
26
+ # time.
27
+ if os.path.exists('token.json'):
28
+ creds = Credentials.from_authorized_user_file('token.json', SCOPES)
29
+ # If there are no (valid) credentials available, let the user log in.
30
+ if not creds or not creds.valid:
31
+ if creds and creds.expired and creds.refresh_token:
32
+ creds.refresh(Request())
33
+ else:
34
+ flow = InstalledAppFlow.from_client_secrets_file(
35
+ 'credentials.json', SCOPES)
36
+ creds = flow.run_local_server(port=0)
37
+ # Save the credentials for the next run
38
+ with open('token.json', 'w') as token:
39
+ token.write(creds.to_json())
40
+
41
+ try:
42
+ service = build('sheets', 'v4', credentials=creds)
43
+
44
+ # Call the Sheets API
45
+ sheet = service.spreadsheets()
46
+ result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
47
+ range=SAMPLE_RANGE_NAME).execute()
48
+ values = result.get('values', [])
49
+
50
+ if not values:
51
+ print('No data found.')
52
+ return
53
+
54
+ print('Name, Major:')
55
+ for row in values:
56
+ # Print columns A and E, which correspond to indices 0 and 4.
57
+ print('%s, %s' % (row[0], row[4]))
58
+ except HttpError as err:
59
+ print(err)
60
+
61
+
62
+ if __name__ == '__main__':
63
+ main()