我可以连接到Google Spreadsheet并添加新行(列表中的实际值),如下所示,它可以正常工作:
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from pprint import pprint
from googleapiclient import discovery
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/spreadsheets.currentonly',
'https://www.googleapis.com/auth/spreadsheets']
credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)
gc = gspread.authorize(credentials)
service = discovery.build('sheets', 'v4', credentials=credentials)
#Name of Spreadsheet
Sheet_Title = "New Spreadsheet Final"
# The ID of the spreadsheet
spreadsheet_id = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # TODO: Update placeholder value.
#Get sheet ID
#Open the wanted Tab
sheet = gc.open(Sheet_Title).worksheet("Tab One")
#Get the wanted range of the sheet
range_name = 'A1:W1000' # TODO: Update placeholder value.
#Add new rows in the Sheet. Values are hardcoded below
values = [
['09/01/2021', 'IT', '8%'],
['08/02/2021', 'NL', '1%']
# Additional rows ...
]
body = {
'values': values
}
#Append the rows in the Google Spreadsheet
result = service.spreadsheets().values().append(
spreadsheetId=spreadsheet_id, range=range_name,
valueInputOption='USER_ENTERED', body=body).execute()
现在我要尝试的是添加新行,但是对于每个单元格(或通常为特定列)添加数据验证。因此,我下去查看了响应。然后,我附加了一个新的行值,其中包括格式和数据验证:
#Values to be added in the original query
value_to_be_added = [
{
"formattedValue": "05/05/2019",
"userEnteredFormat": {
"numberFormat": {
"type": "DATE",
"pattern": "dd/mm/yyyy"
}
},
"dataValidation": {
"condition": {
"type": "DATE_IS_VALID"
},
"strict": "True"
}
},
{
"formattedValue": "DE",
"userEnteredFormat": {
"numberFormat": {
"type": "NUMBER",
"pattern": "#,##0.00"
},
"verticalAlignment": "BOTTOM"
},
"dataValidation": {
"condition": {
"type": "ONE_OF_LIST",
"values": [
{
"userEnteredValue": "UK"
},
{
"userEnteredValue": "ES"
},
{
"userEnteredValue": "IT"
},
{
"userEnteredValue": "DE"
},
{
"userEnteredValue": "AT"
},
{
"userEnteredValue": "NL"
}
]
},
"showCustomUi": "True"
}
},
{
"formattedValue": "4%",
"userEnteredFormat": {
"numberFormat": {
"type": "PERCENT",
"pattern": "0%"
}
}
}
]
换句话说,我已经尝试处理原始响应JSON,而我唯一需要做的就是更新完整文件,但是我找不到正确的更新功能:
#Get request to get the full Google Spreadsheet in a JSON
request = service.spreadsheets().get(spreadsheetId=spreadsheet_id, ranges=range_name, includeGridData=True)
response = request.execute()
#dictionary that will be appended in the values of the response
mydict = {}
#Assign dictionary with the new value. We have one value in this case.
mydict[row_count+1] = value_to_be_added
#print(mydict[row_count+1])
#Add new row in the response.
response['sheets'][0]['data'][0]['rowData'][x]['values'].append(mydict[row_count+1])
#updated response that has to be sent/updated in the API.
new_response = response
有没有办法用更新的响应完全替换/替换原始响应?
原始电子表格:
update.request之后的最终电子表格(我希望如何):
,您将在其中看到一个应用数据验证的新行(可以是X的行数)。
答案 0 :(得分:2)
dd/mm/yyyy
,数据验证,0%
格式的数字和数字。05/05/2019, UK, 8%, 9
的值作为显示值。如果我的理解是正确的,那么该示例脚本如何?在此示例脚本中,我使用了gspread的batch_update
方法。 gspread的batch_upate
方法是Sheets API的电子表格.batchUpdate方法。并且该行由appendCells请求追加。
示例脚本如下。在运行脚本之前,请设置电子表格ID和工作表名称。在此脚本中,Tab One
被用作工作表名称。
gc = gspread.authorize(credentials)
spreadsheet_id = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
sheetName = "Tab One"
spreadsheet = gc.open_by_key(spreadsheet_id)
sheetId = spreadsheet.worksheet(sheetName)._properties['sheetId']
body = {'requests':
[
{
'appendCells':
{
'rows':
[
{
'values':
[
{
'userEnteredFormat':
{
'numberFormat':
{
'type': 'DATE',
'pattern': 'dd/mm/yyyy'
}
},
'dataValidation':
{
'condition':
{
'type': 'DATE_IS_VALID'
},
'strict': True
},
'userEnteredValue':
{
'numberValue': 43590 # This is the serial number of "05/05/2019".
}
},
{
'userEnteredFormat':
{
'numberFormat':
{
'type': 'NUMBER',
'pattern': '#,##0.00'
},
'verticalAlignment': 'BOTTOM'
},
'dataValidation':
{
'condition':
{
'type': 'ONE_OF_LIST',
'values':
[
{
'userEnteredValue': 'UK'
},
{
'userEnteredValue': 'ES'
},
{
'userEnteredValue': 'IT'
},
{
'userEnteredValue': 'DE'
},
{
'userEnteredValue': 'AT'
},
{
'userEnteredValue': 'NL'
}
]
},
'showCustomUi': True
},
'userEnteredValue':
{
'stringValue': 'UK'
}
},
{
'userEnteredFormat':
{
'numberFormat':
{
'type': 'PERCENT',
'pattern': '0%'
}
},
'userEnteredValue':
{
'numberValue': 0.08
}
},
{
'userEnteredValue':
{
'numberValue': 9
}
}
]
}
],
'sheetId': sheetId,
'fields': '*'
}
}
]
}
res = spreadsheet.batch_update(body)
print(res)
05/05/2019
设置为dd/mm/yyyy
格式的日期时,请输入序列号43590
。当您要在for循环中使用请求正文时,以下脚本如何? batchUpdate方法可以与数组一起使用。
gc = gspread.authorize(credentials)
spreadsheet_id = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
sheetName = "Tab One"
spreadsheet = gc.open_by_key(spreadsheet_id)
sheetId = spreadsheet.worksheet(sheetName)._properties['sheetId']
requests = []
for x in range(len(new_values)): # Please set "new_values".
body = {
'appendCells':
{
'rows':
[
{
'values':
[
{
'userEnteredFormat':
{
'numberFormat':
{
'type': 'DATE',
'pattern': 'dd/mm/yyyy'
}
},
'dataValidation':
{
'condition':
{
'type': 'DATE_IS_VALID'
},
'strict': True
},
'userEnteredValue':
{
'numberValue': new_values[x][0]
}
},
{
'userEnteredFormat':
{
'numberFormat':
{
'type': 'NUMBER',
'pattern': '#,##0.00'
},
'verticalAlignment': 'BOTTOM'
},
'dataValidation':
{
'condition':
{
'type': 'ONE_OF_LIST',
'values':
[
{
'userEnteredValue': 'UK'
},
{
'userEnteredValue': 'ES'
},
{
'userEnteredValue': 'IT'
},
{
'userEnteredValue': 'DE'
},
{
'userEnteredValue': 'AT'
},
{
'userEnteredValue': 'NL'
}
]
},
'showCustomUi': True
},
'userEnteredValue':
{
'stringValue': new_values[x][1]
}
},
{
'userEnteredFormat':
{
'numberFormat':
{
'type': 'PERCENT',
'pattern': '0%'
}
},
'userEnteredValue':
{
'numberValue': new_values[x][2]
}
},
{
'userEnteredValue':
{
'numberValue': new_values[x][2]
}
}
]
}
],
'sheetId': sheetId,
'fields': '*'
}
}
requests.append(body)
res = spreadsheet.batch_update({'requests':requests})
print(res)
答案 1 :(得分:0)
我的版本基于Tanaike的答案:
#List of rows with values
new_values = [[43590,'UK',0.08,9],[43590,'DE',0.07,8]]
#connect to the google sheet and tab
sheetName = "Tab One"
spreadsheet = gc.open_by_key(spreadsheet_id)
sheetId = spreadsheet.worksheet(sheetName)._properties['sheetId']
#Add each value/row
for x in range(len(new_values)):
#print(new_values[x])
body = {'requests':
[
{
'appendCells':
{
'rows':
[
{
'values':
[
{
'userEnteredFormat':
{
'numberFormat':
{
'type': 'DATE',
'pattern': 'dd/mm/yyyy'
}
},
'dataValidation':
{
'condition':
{
'type': 'DATE_IS_VALID'
},
'strict': True
},
'userEnteredValue':
{
'numberValue': new_values[x][0] # This is the serial number of "05/05/2019".
}
},
{
'userEnteredFormat':
{
'numberFormat':
{
'type': 'NUMBER',
'pattern': '#,##0.00'
},
'verticalAlignment': 'BOTTOM'
},
'dataValidation':
{
'condition':
{
'type': 'ONE_OF_LIST',
'values':
[
{
'userEnteredValue': 'UK'
},
{
'userEnteredValue': 'ES'
},
{
'userEnteredValue': 'IT'
},
{
'userEnteredValue': 'DE'
},
{
'userEnteredValue': 'AT'
},
{
'userEnteredValue': 'NL'
}
]
},
'showCustomUi': True
},
'userEnteredValue':
{
'stringValue': new_values[x][1]
}
},
{
'userEnteredFormat':
{
'numberFormat':
{
'type': 'PERCENT',
'pattern': '0%'
}
},
'userEnteredValue':
{
'numberValue': new_values[x][2]
}
},
{
'userEnteredValue':
{
'numberValue': new_values[x][3]
}
}
]
}
],
'sheetId': sheetId,
'fields': '*'
}
}
]
}
res = spreadsheet.batch_update(body)
身体在每个循环中被拉动。如果您认为这不是最好的方法(循环身体),则可以评论任何替代方法。循环并在主体对象中附加values
数组可能会更容易。