使用这些函数从第一个工作表中获取数据,然后获取特定的行和列来生成报表。当我试图在一个名为 "ReportList "的单独空白表上生成报表时,当我知道credentials.json文件是正确的时,我得到了一个400错误,因为我也尝试过重新认证。我还有两个用于不同认证范围的凭证文件。
def get_google_sheet(spreadsheet_id, range_name):
# Retrieve sheet data using OAuth credentials and Google Python API.
global scopes
global gsheet
scopes = ['https://www.googleapis.com/auth/spreadsheets']
# Setup the Sheets API
store = file.Storage('credentials1.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', scopes)
creds = tools.run_flow(flow, store)
service = build('sheets', 'v4', http=creds.authorize(Http()))
# Call the Sheets API
gsheet = service.spreadsheets().values().get(spreadsheetId=spreadsheet_id, range=range_name).execute()
return gsheet
def gsheet2df(gsheet):
# Converts Google sheet data to a Pandas DataFrame.
header = gsheet.get('values', [])[0] # Assumes first line is header!
values = gsheet.get('values', [])[1:] # Everything else is data.
#header = values[0]
if not values:
print('No data found.')
else:
df = pd.DataFrame.from_records(values)
df.columns = header
return df
def Export_Data_To_Sheets():
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', scopes)
creds = tools.run_flow(flow, store)
service = build('sheets', 'v4', http=creds.authorize(Http()))
RANGE_AND_SHEET = "ReportList!A1:E500"
response_date = service.spreadsheets().values().update(
spreadsheetId=SPREADSHEET_ID,
valueInputOption='RAW',
range=RANGE_AND_SHEET,
body=dict(
majorDimension='ROWS',
values=df.T.reset_index().T.values.tolist())
).execute()
print('Sheet successfully Updated')
当我只使用范围而不识别表时,它没有问题。使用范围和表时,我得到这个错误。
Traceback (most recent call last):
File "/Users/adaniel/PycharmProjects/EmailAutomation/venv/AutoEmailScript/test.py", line 126, in <module>
Export_Data_To_Sheets()
File "/Users/adaniel/PycharmProjects/EmailAutomation/venv/AutoEmailScript/test.py", line 68, in Export_Data_To_Sheets
response_date = service.spreadsheets().values().update(
File "/Users/adaniels/PycharmProjects/EmailAutomation/venv/lib/python3.8/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "/Users/adaniels/PycharmProjects/EmailAutomation/venv/lib/python3.8/site-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/*******yAABhNJvARr9BzsVLvCYSfpcvQAmpWESL-DJI/values/%28%27ReportList%21%27%2C%20%27A1%3AE500%27%29?valueInputOption=RAW&alt=json returned "Invalid JSON payload received. Unexpected token.
House", "10/19/19", NaN, NaN, NaN], ["Co
^">
该 A1 notation
需要 !
之间的表名和范围,所以。
ReportList!A1:E500
而不是
ReportListA1:E500
.
请求的正确语法包含值输入选项和嵌套到请求体中的值。
response_date = service.spreadsheets().values().update(
spreadsheetId=SPREADSHEET_ID,
valueInputOption='RAW',
range=RANGE_AND_SHEET,
body=#your values here
).execute()
请注意,对于spreadsheets.values.update与spreadsheets.values.batchUpdate相反,你不能指定主要维度。