Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

namedTables show up only as bandedRanges #2541

Open
Frick-David opened this issue Jan 5, 2025 · 0 comments
Open

namedTables show up only as bandedRanges #2541

Frick-David opened this issue Jan 5, 2025 · 0 comments

Comments

@Frick-David
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant