通过apiv4 python将值插入google工作表

2024-04-24 08:00:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要帮助在表格中插入值。这就是我到目前为止所拥有的基本上是将系统连接到GoogleSheetsAPI的代码

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

from pprint import pprint

from googleapiclient import discovery

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = 'some id '
SAMPLE_RANGE_NAME = 'Sheet1!A1:F3'

def main():
    """Shows basic usage of the Sheets API.
    Prints values from a sample spreadsheet.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=726)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('sheets', 'v4', credentials=creds)



    sheet = service.spreadsheets()
    result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                                range=SAMPLE_RANGE_NAME).execute()
    values = result.get('values', [])

    if not values:
        print('No data found.')
    else:
        print('Name, Major:')
        for row in values:
            # Print columns A and E, which correspond to indices 0 and 4.
            print(row)

if __name__ == '__main__':
    main()

这段代码工作,它打印出表格中的值,这基本上就是纪录片中写的。在工作表中插入值时遇到问题

我从一个网站上搜集了一些信息,我需要把这些信息放到工作表中我不知道该怎么做我试图了解更新工作表中的值是如何工作的,但我一直在代码中出错这是我写的

values = [
    [
        100, 300, 400 
    ],
    # Additional rows ...
]
body = {
    'values': values
}
result = service.spreadsheets().values().update(
    spreadsheetId=some id, range=SAMPLE_RANGE_NAME,
    valueInputOption='Raw', body=body).execute()
print('{0} cells updated.'.format(result.get('updatedCells')))

但它给我带来了一个pylint错误,即在值旁边的[上的标识不正确

你能告诉我我做错了什么,或者建议一种更好的方法将信息插入到我想看到的表格中吗