diff --git a/Google Sheets/Google_Sheets_List_sheets_from_spreadsheet.ipynb b/Google Sheets/Google_Sheets_List_sheets_from_spreadsheet.ipynb index 0fefb512af..efd0142888 100644 --- a/Google Sheets/Google_Sheets_List_sheets_from_spreadsheet.ipynb +++ b/Google Sheets/Google_Sheets_List_sheets_from_spreadsheet.ipynb @@ -111,11 +111,13 @@ }, "outputs": [], "source": [ - "import os\n", - "import pickle\n", - "import googleapiclient.discovery\n", - "from google_auth_oauthlib.flow import InstalledAppFlow\n", - "from google.auth.transport.requests import Request" + "try:\n", + " import gspread\n", + " from oauth2client.service_account import ServiceAccountCredentials\n", + "except ImportError:\n", + " !pip install gspread oauth2client\n", + " import gspread\n", + " from oauth2client.service_account import ServiceAccountCredentials" ] }, { @@ -127,8 +129,27 @@ }, "source": [ "### Setup variables\n", - "- **SCOPES**: `https://www.googleapis.com/auth/spreadsheets.readonly`\n", - "- **SPREADSHEET_ID**: ID of the spreadsheet to list sheets from" + "**Pre-requisite**\n", + "- [Create a service account and download JSON](https://cloud.google.com/iam/docs/service-accounts-create)\n", + "- [Enable Google Sheets API](https://console.cloud.google.com/apis/library/sheets.googleapis.com)\n", + "- Share your Google Sheet spreadsheet with service account client email\n", + "\n", + "**Mandatory**\n", + "- `credential_path`: path to access service account.\n", + "- `spreadsheet_id`: ID of the spreadsheet to list sheets from ." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a75d65c1-1969-4f7c-9a19-819a06e03e9d", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "credential_path = \"./credentials.json\"\n", + "spreadsheet_id = '1bt2D7DPsmPYTQI0IOziAxYMbI9eRADN8gxTKMSmE7aw' # Replace with the id of your existing spreadsheet" ] }, { @@ -161,7 +182,7 @@ "tags": [] }, "source": [ - "This function will list all the sheets from a Google Sheets spreadsheet." + "The following snippet authorizes and gets the sheets associated with a spreadsheet ." ] }, { @@ -174,38 +195,16 @@ }, "outputs": [], "source": [ - "def list_sheets(spreadsheet_id):\n", - " \"\"\"\n", - " List all the sheets from a Google Sheets spreadsheet.\n", - "\n", - " Parameters:\n", - " spreadsheet_id (str): ID of the spreadsheet to list sheets from\n", - "\n", - " Returns:\n", - " list: list of sheets\n", - " \"\"\"\n", - " # Setup credentials\n", - " SCOPES = [\"https://www.googleapis.com/auth/spreadsheets.readonly\"]\n", - " creds = None\n", - " if os.path.exists(\"token.pickle\"):\n", - " with open(\"token.pickle\", \"rb\") as token:\n", - " creds = pickle.load(token)\n", - " if not creds or not creds.valid:\n", - " if creds and creds.expired and creds.refresh_token:\n", - " creds.refresh(Request())\n", - " else:\n", - " try:\n", - " flow = InstalledAppFlow.from_client_secrets_file(\"credentials.json\", SCOPES)\n", - " creds = flow.run_console()\n", - " except Exception as e:\n", - " print(f\"Error during OAuth flow: {str(e)}\")\n", - " return None\n", - " with open(\"token.pickle\", \"wb\") as token:\n", - " pickle.dump(creds, token)\n", - " # List sheets\n", - " service = googleapiclient.discovery.build(\"sheets\", \"v4\", credentials=creds)\n", - " sheets = service.spreadsheets().get(spreadsheetId=spreadsheet_id).execute()\n", - " return sheets[\"sheets\"]" + "try:\n", + " scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']\n", + " credentials = ServiceAccountCredentials.from_json_keyfile_name(credential_path, scope)\n", + " client = gspread.authorize(credentials)\n", + " spreadsheet = client.open_by_key(spreadsheet_id)\n", + " sheets = spreadsheet.worksheets()\n", + "except gspread.exceptions.SpreadsheetNotFound:\n", + " print(f\"Spreadsheet with ID '{spreadsheet_id}' not found.\")\n", + "except gspread.exceptions.APIError as e:\n", + " print(f\"An error occurred while accessing the spreadsheet: {e}\")" ] }, { @@ -240,14 +239,10 @@ }, "outputs": [], "source": [ - "# Setup variables\n", - "SPREADSHEET_ID = \"1bt2D7DPsmPYTQI0IOziAxYMbI9eRADN8gxTKMSmE7aw\"\n", - "# List sheets\n", - "sheets = list_sheets(SPREADSHEET_ID)\n", - "# Display result\n", - "print(f\"Sheets from spreadsheet {SPREADSHEET_ID}:\")\n", + "# List the sheets in the spreadsheet\n", + "print(\"Sheets in the spreadsheet:\")\n", "for sheet in sheets:\n", - " print(f'- {sheet[\"properties\"][\"title\"]}')" + " print(sheet.title)" ] }, {