I have a little program that is supposed to return all of the charts in a Google Sheets document. The program is as follows:
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
import os
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
def get_sheets_service():
"""Authenticates and returns a Google Sheets API service object."""
creds = None
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
with open('token.json', 'w') as token:
token.write(creds.to_json())
service = build('sheets', 'v4', credentials=creds)
return service
def find_chart_ids(spreadsheet_id):
"""Finds and prints the chart IDs in a Google Sheet."""
service = get_sheets_service()
try:
spreadsheet = service.spreadsheets().get(
spreadsheetId=spreadsheet_id,
).execute()
print(f'spreadsheet: {spreadsheet}')
chart_ids = []
for sheet in spreadsheet.get('sheets', []):
#print(f'Sheet: {sheet["spreadsheetId"]}')
#print(f'Sheet: {sheet.__dict__}')
for chart in sheet.get('charts', []):
print(f'Chart: {chart}')
chart_ids.append(chart['chartId'])
return chart_ids
except Exception as e:
print(f"An error occurred: {e}")
return []
if __name__ == '__main__':
# Replace with your actual spreadsheet ID
SPREADSHEET_ID = '[redacted]'
chart_ids = find_chart_ids(SPREADSHEET_ID)
if chart_ids:
print("Found chart IDs:")
for chart_id in chart_ids:
print(chart_id)
else:
print("No charts found or an error occurred.")
But it only finds one of the two charts that are in a given sheet. I know there are two charts in the one worksheet as I can visually see when I use the WebU to view the sheetnt that there are two charts but the output from the above program only shows one Chart: item.
I thought maybe this was some kind of issue with only returning the first of many items and so I tried deleting the first chart, but that resulted in showing now Chart: lines.
A38:AO,C38:Cwhen I hitenterin the field, it auto-populates the last row in the range, closing it. I'm doubtful it will continue to get updated as new rows are added at this point. I guess I will see tomorrow when this gets updated again with a new row.ctrl-enddon't do what I want them to do. All to work around something that should work as it is. I guess my main reason for asking this was to find out if I was doing something obviously wrong. I guess now I need to open a bug report. Thanks for you help!