使用Python更新Google Sheet APIv4中的值

时间:2017-07-10 12:45:36

标签: python google-sheets-api google-apis-explorer

我使用以下python代码处理Google表格:

#!/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 个答案:

答案 0 :(得分:1)

错误消息说明问题:请求范围内的内容[QQ!A1:A5],但尝试写入[B]栏。

您编写的数据超出了您想要编写的范围,因此服务器失败而不是让您意外覆盖其他数据。

要修复,请增加请求的范围或仅在其中写入数据。

编辑:.基于重新读取代码,看起来您想要编写单个列。默认情况下,主要输入维度为&#34; row&#34;。也就是说,[[1,2],[3,4]]在A1中放置1,在B1中放置2,在A2中放置3,在B2中放置4。您可以通过指定数据来确定输入,例如[[1],[2],[3]]等。或者将majorDimension参数更改为COLUMNS