代码之家  ›  专栏  ›  技术社区  ›  Slinbody Yang

使用Python更新Google Sheet APIv4中的值

  •  5
  • Slinbody Yang  · 技术社区  · 8 年前

    #!/usr/bin/python
    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
    
    SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
    CLIENT_SECRET_FILE = 'client_secret.json'
    APPLICATION_NAME = 'Google Sheets API Python Quickstart'
    
    
    def get_credentials():
    
        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():
        credentials = get_credentials()
        print("get_credentials DONE")
        http = credentials.authorize(httplib2.Http())
        discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                        'version=v4')
        service = discovery.build('sheets', 'v4', http=http,
                                  discoveryServiceUrl=discoveryUrl)
    
        spreadsheetid = '1tMtwIJ1NKusQRMrF0FnV6WVaLJ1MUzun-p_rgO06zh0'
        rangeName = "QQ!A1:A5"
    
        values = [
            [
                500,400,300,200,100,
            ],
        ]
    
        Body = {
        'values' : values,
        }
    
        result = service.spreadsheets().values().update(
        spreadsheetId=spreadsheetid, range=rangeName,
        valueInputOption='RAW', body=Body).execute()
    
        print("Writing OK!!")
    
        result = service.spreadsheets().values().get(
            spreadsheetId=spreadsheetid, range=rangeName).execute()
        values = result.get('values', [])
    
        if not values:
            print('No data found.')
        else:
            print('Name :')
            for row in values:
                # Print columns A and E, which correspond to indices 0 and 4.
                print('%s' % (row[0]))
    
    
    if __name__ == '__main__':
        main()
    

    运行代码后:

    Traceback (most recent call last):
      File "google-sheet.py", line 100, in <module>
        main()
      File "google-sheet.py", line 82, in main
        valueInputOption='RAW', body=Body).execute()
      File "/usr/local/lib/python2.7/dist-packages/oauth2client/_helpers.py", line 133, in positional_wrapper
        return wrapped(*args, **kwargs)
      File "/usr/local/lib/python2.7/dist-packages/googleapiclient/http.py", line 840, in execute
        raise HttpError(resp, content, uri=self.uri)
    googleapiclient.errors.HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/1tMtwIJ1NKusQRMrF0FnV6WVaLJ1MUzun-p_rgO06zh0/values/QQ%21A1%3AA5?alt=json&valueInputOption=RAW returned "Requested writing withinrange [QQ!A1:A5], but tried writing to column [B]">
    

    但如果我只读取值,它就可以完美地工作。 没有相关的有用信息。

    在Sam Berlin的帮助下,
    只需将正文内容:

    Body = {
    'values' : values,
    'majorDimension' : 'COLUMNS',
    }
    

    它工作得很好!!

    1 回复  |  直到 8 年前
        1
  •  2
  •   Sam Berlin    8 年前

    错误消息指出问题:请求在[QQ!A1:A5]范围内写入,但尝试写入列[B]。

    您正在写入的数据超过了范围所说的要写入的数据量,因此服务器正在发生故障,而不是让您意外地覆盖其他数据。

    [[1,2],[3,4]] 将1放在A1中,2放在B1中,3放在A2中,4放在B2中。您可以通过这样指定数据来修复输入,例如[1]、[2]、[3]等。或者通过更改 majorDimension COLUMNS .