Open
Description
So the API does not expose namedRanges such as namedTables to add rows to.
I have to use the following:
def add_row_and_adjust_banding(service, spreadsheet_id, sheet_name, new_row):
"""
Adds a row to a sheet and adjusts the existing banded range accordingly.
Args:
service: The Google Sheets API service object.
spreadsheet_id: The ID of the spreadsheet.
sheet_name: The name of the sheet.
new_row: A list representing the values for the new row.
Returns:
The result of the batchUpdate operation.
"""
# Get the sheet ID
sheet_metadata = service.spreadsheets().get(spreadsheetId=spreadsheet_id,
fields='sheets.properties.sheetId,sheets.properties.title').execute()
our_sheet = None
for sheet in sheet_metadata.get('sheets', []):
if sheet['properties']['title'] == sheet_name:
our_sheet = sheet
break
else:
raise ValueError(f"Sheet '{sheet_name}' not found.")
# Add the new row
append_request_body = {
'requests': [{
'appendCells': {
'rows': [
{'values': [{'userEnteredValue': {'stringValue': str(val)}} for val in new_row]}
],
'sheetId': our_sheet['properties']['sheetId'],
'fields': 'userEnteredValue'
}
}]
}
append_result = service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id,
body=append_request_body).execute()
# Get the existing bandedRanges (if any)
sheet_data = service.spreadsheets().get(spreadsheetId=spreadsheet_id).execute()
our_sheet = None
for sheet in sheet_data.get('sheets', []):
if sheet['properties']['title'] == sheet_name:
our_sheet = sheet
break
else:
raise ValueError(f"Sheet '{sheet_name}' not found.")
if our_sheet:
print(json.dumps(our_sheet, indent=4))
our_banded_range = our_sheet['bandedRanges']
our_banded_range[0]['range']['endRowIndex'] += 1```
to get a banded range instead of our_sheet['namedRanges'] and add to that.
Metadata
Metadata
Assignees
Labels
No labels