使用 Python 更新 Google Sheet APIv4 中的值

Update value in Google Sheet APIv4 with Python

我用下面的python代码来处理Google sheet:

#!/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]">

但如果我只读取值,它就可以完美运行。 我在 Google 中找到了很多信息。 暂无相关有用信息。

经过 Sam Berlin 的帮助,
只放正文内容:

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

而且效果很好!!

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

您写入的数据比您的范围显示的要写入的数据多,因此服务器出现故障,而不是让您意外覆盖其他数据。

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

编辑:。根据重新阅读您的代码,您似乎想写一个专栏。默认情况下,主要输入维度是 "row"。即 [[1,2],[3,4]] 将 1 放入 A1,将 2 放入 B1,将 3 放入 A2,将 4 放入 B2。您可以通过以这种方式指定数据来修复输入,例如 [[1],[2],[3]] 等。或者将 majorDimension 参数更改为 COLUMNS.