0

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.

5
  • I update the data range in the one that is not being returned, almost daily. The whole point of trying to fetch it's data is to get the chart's id so that I can have the tool that I use to update the sheet by API also update the chart's data range. Commented Oct 18 at 13:44
  • Perhaps you don't need to update the data range in the first place? Use an open-ended reference to make the data range reach all the way down to the bottom of the sheet. Just make sure the cells below the data are blank. Blank cells won't get plotted in the chart. Commented Oct 18 at 17:04
  • Unless I am misunderstanding you, I don't think that works. When I try to change the Data Range to A38:AO,C38:C when I hit enter in 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. Commented Oct 19 at 15:44
  • Add say 1000 blank rows in the sheet, and make the data range extend all the way to the bottom. Don't add rows when you add data. Add new data in the existing blank rows. Commented Oct 19 at 15:53
  • While I appreciate that you are just trying to help work around what appears to be a bug, now I am writing new code to try to figure out where the first blank line is that I need to add the new line of data. And also handle running out of blank lines. And having a ton of blank lines at the bottom of my sheet meaning shortcuts like ctrl-end don'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! Commented Oct 19 at 20:15

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.