Я могу подключиться к электронной таблице Google и добавить новые строки (фактические значения из списка), как показано ниже, и это работает:
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
Существует ли способ полностью обновить / заменить исходный ответ обновленным?
Исходная таблица:
![enter image description here](https://i.stack.imgur.com/UqQ4k.png)
Последняя таблица после моего запроса update.request (как я хочу):
![enter image description here](https://i.stack.imgur.com/UfopN.png)
где вы можете увидеть одну новую строку с применением проверки данных (это может быть количество строк X).