Python quickstart.py适用于我的Google表格电子表格

时间:2017-10-05 01:09:44

标签: python google-apps-script

我使用Python27成功实施了Google Cloud API客户端 这里: https://developers.google.com/sheets/api/quickstart/python?refresh=1

并运行示例代码quickstart.py,确定。

我安装了--upgrade google-api-python-client。

我天真地以为我可以更改电子表格ID和目标范围,它会起作用。错!

这是我的代码:

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()

任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:1)

我终于开始工作了。感谢tanaike的帮助。这是代码:

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()

答案 1 :(得分:0)

你的脚本有效。但是必须修改一个变量。

来自:

spreadsheetId = '1ksrW3mUJvPJkmv1HZyWC9Ma1Fbe1cX0CDegSjW2yIAY/edit#gid=0'

致:

spreadsheetId = '1ksrW3mUJvPJkmv1HZyWC9Ma1Fbe1cX0CDegSjW2yIAY'

注意:

您的电子表格ID为1ksrW3mUJvPJkmv1HZyWC9Ma1Fbe1cX0CDegSjW2yIAY。电子表格ID的详细信息为here

如果您在完成上述修改后脚本无法正常工作,请随时告诉我。那时,请告诉我们错误信息。

编辑:

来自" B4的数据:C9"是一个包含2行和6列的列表。列表的第一个索引是0.错误main() Line 78 in main print('%s, %s' % (row[1], row[2])) IndexError: List index out of range的原因是这个。所以请修改如下。

来自:

print('%s, %s' % (row[1], row[2]))

致:

print('%s, %s' % (row[0], row[1]))