Skip to content

Commit

Permalink
revised changes 01
Browse files Browse the repository at this point in the history
  • Loading branch information
MSaiKiran9 committed Nov 4, 2023
1 parent f6c64a8 commit 3497657
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 340 deletions.
104 changes: 36 additions & 68 deletions Google Sheets/Google_Sheets_Create_new_sheet.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
"tags": []
},
"source": [
"**Description:** This notebook will show how to create a new sheet in Google Sheets using Python. It is useful for organizations that need to create new sheets in Google Sheets."
"**Description:** This notebook will show how to create a new sheet in Google Sheets using Python . It is useful for organizations that need to create new sheets in Google Sheets."
]
},
{
Expand Down Expand Up @@ -111,18 +111,13 @@
},
"outputs": [],
"source": [
"import naas\n",
"import json\n",
"try:\n",
" from google.oauth2 import service_account\n",
" from googleapiclient.discovery import build\n",
" from googleapiclient.errors import HttpError\n",
"except ModuleNotFoundError:\n",
" !pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib\n",
" from google.oauth2 import service_account\n",
" from googleapiclient.discovery import build\n",
" from googleapiclient.errors import HttpError\n",
"#step 1: make sure all these modules are installed and imported !"
" 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"
]
},
{
Expand All @@ -134,9 +129,15 @@
},
"source": [
"### Setup variables\n",
"- **SCOPES**: list of scopes to be used in the authentication\n",
"- **SPREADSHEET_ID**: ID of the spreadsheet\n",
"- **SHEET_NAME**: name of the new sheet"
"**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_name`: Name of the spreadsheet you want to create the new sheet in\n",
"- `sheet_name`: Name of the new sheet"
]
},
{
Expand All @@ -149,10 +150,9 @@
},
"outputs": [],
"source": [
"SCOPES = [\"https://www.googleapis.com/auth/drive\", \"https://www.googleapis.com/auth/spreadsheets\"]\n",
"sheetName=\"sheet1\"\n",
"# SCOPES are used in the code to define access permissions \n",
"# sheetName is our required output sheet name (edit the name as required )."
"credential_path = \"./credentials.json\"\n",
"spreadsheet_name = \"My_Spreadsheet\"\n",
"sheet_name = \"custom sheet 2\""
]
},
{
Expand All @@ -177,17 +177,6 @@
"### Create new sheet"
]
},
{
"cell_type": "markdown",
"id": "9ae12770-9a68-4e9f-9155-41e9cee1e2ff",
"metadata": {
"papermill": {},
"tags": []
},
"source": [
"This function will create a new sheet in the spreadsheet with the name specified in the variable SHEET_NAME."
]
},
{
"cell_type": "code",
"execution_count": null,
Expand All @@ -198,44 +187,23 @@
},
"outputs": [],
"source": [
"# Step 2: Define the service account credentials as a dictionary \n",
"# Step 3: (goto google cloud console > your-project > IAM and Admin > service accounts > fill in the details.)\n",
"# Step 4: then generate a key & save it as a secret string using : naas.secret.add(name=\"key\",secret=json.dumps(x.json))\n",
"# Define the scope and credentials\n",
"scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']\n",
"credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)\n",
"\n",
"credentials_info = json.loads(naas.secret.get(name=\"key\"))\n",
"\n",
"def create_google_sheet(credentials_info, personal_email):\n",
" # Use the credentials dictionary to create the service account credentials\n",
" creds = service_account.Credentials.from_service_account_info(credentials_info, scopes=SCOPES)\n",
"\n",
" try:\n",
" service = build('sheets', 'v4', credentials=creds)\n",
"\n",
" # Create a new spreadsheet\n",
" spreadsheet = service.spreadsheets().create(body={\"properties\": {\"title\": \"My New Spreadsheet\"}}).execute()\n",
"\n",
" print(f\"Created new spreadsheet with ID: {spreadsheet['spreadsheetId']}\")\n",
"\n",
" # Access and print the URL of the created Google Sheet\n",
" sheet_url = spreadsheet.get(\"spreadsheetUrl\")\n",
" print(\"URL of the created Google Sheet:\", sheet_url)\n",
"\n",
" # Share the Google Sheet with your personal email or anyone using the Google Drive API\n",
" drive_service = build('drive', 'v3', credentials=creds)\n",
" permission = {\n",
" 'type': 'user',\n",
" 'role': 'writer',\n",
" 'emailAddress': personal_email\n",
" }\n",
" drive_service.permissions().create(fileId=spreadsheet['spreadsheetId'], body=permission).execute()\n",
"\n",
" print(f\"Shared the Google Sheet with {personal_email}\")\n",
"\n",
" except HttpError as err:\n",
" print(err)\n",
"# Authenticate and open the spreadsheet\n",
"try:\n",
" # Authenticate and open the existing spreadsheet\n",
" client = gspread.authorize(credentials)\n",
" spreadsheet = client.open(spreadsheet_name)\n",
"except:\n",
" # If the spreadsheet doesn't exist, create a new one and open it\n",
" client = gspread.authorize(credentials)\n",
" spreadsheet = client.create(spreadsheet_name)\n",
"\n",
"# Specify your personal / anyother account Gmail address.\n",
"personal_email = 's2612369@gmail.com'"
"# Create a new sheet\n",
"new_spreadsheet = spreadsheet.add_worksheet(title=sheet_name, rows=\"100\", cols=\"20\")\n",
"print(f\"A new sheet named '{sheet_name}' has been created successfully.\")"
]
},
{
Expand Down Expand Up @@ -270,8 +238,8 @@
},
"outputs": [],
"source": [
"# step 5: Call the function to create the Google Sheet and share it with your anyother accounts.\n",
"create_google_sheet(credentials_info, personal_email)"
"print(\"Go To Spreadsheet\")\n",
"print(f\"https://docs.google.com/spreadsheets/d/{new_spreadsheet.url.split('spreadsheets')[1]}\")"
]
},
{
Expand Down
Loading

0 comments on commit 3497657

Please sign in to comment.