[英]Python quickstart.py adapted to my Google Sheets spreadsheet
I implemented the Google Cloud API Client successfully using Python27 from here: https://developers.google.com/sheets/api/quickstart/python?refresh=1我从这里使用 Python27 成功实现了 Google Cloud API 客户端: https : //developers.google.com/sheets/api/quickstart/python? refresh =1
and ran the sample code, quickstart.py, ok.并运行示例代码,quickstart.py,ok。
I installed install --upgrade google-api-python-client.我安装了 install --upgrade google-api-python-client。
I naively thought I could just change the spreadsheet IDs and the target range and it would work.我天真地认为我可以只更改电子表格 ID 和目标范围,它会起作用。 Wrong!
错误的!
Here is my code:这是我的代码:
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
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'
def get_credentials():
"""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.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_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:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, 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
def main():
"""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/ \ #continued next line
1ksrW3mUJvPJkmv1HZyWC9Ma1Fbe1cX0CDegSjW2yIAY/edit
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
'version=v4')
service = discovery.build('sheets', 'v4', http=http,
discoveryServiceUrl=discoveryUrl)
spreadsheetId = '1ksrW3mUJvPJkmv1HZyWC9Ma1Fbe1cX0CDegSjW2yIAY/edit#gid=0'
rangeName = 'Class Data!B4:C9'
result = service.spreadsheets().values().get(
spreadsheetId=spreadsheetId, range=rangeName).execute()
values = result.get('values', [])
if not values:
print('No data found.')
else:
print('Name, Major:')
for row in values:
# Print columns B and C, which correspond to indices 2 and 3.
print('%s, %s' % (row[1], row[2]))
if __name__ == '__main__':
main()
Any help appreciated!任何帮助表示赞赏!
Your script works.你的脚本有效。 But one variable has to be modified.
但是必须修改一个变量。
spreadsheetId = '1ksrW3mUJvPJkmv1HZyWC9Ma1Fbe1cX0CDegSjW2yIAY/edit#gid=0'
spreadsheetId = '1ksrW3mUJvPJkmv1HZyWC9Ma1Fbe1cX0CDegSjW2yIAY'
Your spreadsheet ID is 1ksrW3mUJvPJkmv1HZyWC9Ma1Fbe1cX0CDegSjW2yIAY
.您的电子表格 ID 是
1ksrW3mUJvPJkmv1HZyWC9Ma1Fbe1cX0CDegSjW2yIAY
。 The detail information of Spreadsheet ID is here .电子表格 ID 的详细信息在这里。
If the script didn't work after you did above modification, feel free to tell me.如果您在进行上述修改后脚本不起作用,请随时告诉我。 At that time, please show us the error message.
届时,请向我们展示错误信息。
The data from "B4:C9" is a list with 2 rows and 6 columns. “B4:C9”中的数据是一个2行6列的列表。 The first index of list is 0. The reason of the error
main() Line 78 in main print('%s, %s' % (row[1], row[2])) IndexError: List index out of range
is this. list 的第一个索引为 0。
main() Line 78 in main print('%s, %s' % (row[1], row[2])) IndexError: List index out of range
中的错误main() Line 78 in main print('%s, %s' % (row[1], row[2])) IndexError: List index out of range
的原因main() Line 78 in main print('%s, %s' % (row[1], row[2])) IndexError: List index out of range
是这个。 So please modify as follows.所以请修改如下。
print('%s, %s' % (row[1], row[2]))
print('%s, %s' % (row[0], row[1]))
I finally got it to work.我终于让它工作了。 Thanks to tanaike for his help.
感谢田池的帮助。 Here is the code:
这是代码:
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
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'
def get_credentials():
"""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.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_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:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, 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
def main():
"""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/insertSpreadSheetID/edit
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
'version=v4')
service = discovery.build('sheets', 'v4', http=http,
discoveryServiceUrl=discoveryUrl)
spreadsheetId = 'spreadsheetId'
rangeName = 'A1:B9'
result = service.spreadsheets().values().get(
spreadsheetId=spreadsheetId, range=rangeName).execute()
values = result.get('values', [])
if not values:
print('No data found.')
else:
print('Name, Major:')
for row in values:
# Print columns B and C, which correspond to indices 2 and 3.
print('%s, %s' % (row[0], row[1]))
if __name__ == '__main__':
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.