简体   繁体   English

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

[英]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.但是必须修改一个变量。

From :从 :

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

To :到 :

spreadsheetId = '1ksrW3mUJvPJkmv1HZyWC9Ma1Fbe1cX0CDegSjW2yIAY'

Note :笔记 :

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.届时,请向我们展示错误信息。

Edit :编辑 :

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.所以请修改如下。

From :从 :

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

To :到 :

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.

相关问题 尝试使用python访问“google drive”时出错(google quickstart.py源代码) - Error trying to access “google drive” with python (google quickstart.py source code) Google API quickstart.py 错误 KeyError: '_module' - Google API quickstart.py error KeyError: '_module' 由于 JSONDecodeError:额外数据,Google 的 quickstart.py 未连接到 Google Workspace API - Google's quickstart.py not connecting to Google Workspace API because of JSONDecodeError: Extra data Google Drive API Quickstart.py 错误 400:redirect_uri_mismatch - Google Drive API Quickstart.py Error 400: redirect_uri_mismatch Gmail API quickstart.py脚本返回KeyError'_module' - Gmail API quickstart.py script returns KeyError '_module' 由于硒问题,Quickstart.py无法运行 - Quickstart.py failed to run due to selenium issue Google 表格 Python 快速入门需要定期登录 - Google Sheets Python Quickstart requires sign in regularly 使用python3访问Google表格上的电子表格 - Accessing a spreadsheet on Google Sheets using python3 用于电子表格的Google API Explorer返回属性-如何在Python快速入门中获取属性(文件名)? - Google API Explorer for Spreadsheet returns properties - How do I get properties (filename) in Python Quickstart? 适用于python的Google Sheets API快速入门教程会为有效的OAuth2凭据生成403错误 - Google Sheets API quickstart tutorial for python produces 403 error for valid OAuth2 credentials
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM