Using gspread to extract sheet ID - python

Can't seem to find any answer to this, but are there any functions/methods which can get a worksheet ID?
Currently, my code looks like this:
scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
....code to authorize credentials goes here....
sheet = client.open(str(self.googleSheetFile)).worksheet(str(self.worksheet))
client.import_csv('abcdefg1234567abcdefg1234567', contents)
but I don't want to hardcode the abcdefg1234567abcdefg1234567. Is there anything I can do, like sheet.id()?

I believe your goal as follows.
In order to use import_csv, you want to retrieve the Spreadsheet ID from sheet = client.open(str(self.googleSheetFile)).worksheet(str(self.worksheet)).
You want to achieve this using gspread with python.
In this case, you can retrieve the Spreadsheet ID from client.open(str(self.googleSheetFile)). So please modify your script as follows.
From:
sheet = client.open(str(self.googleSheetFile)).worksheet(str(self.worksheet))
client.import_csv('abcdefg1234567abcdefg1234567', contents)
To:
spreadsheet = client.open(str(self.googleSheetFile))
sheet = spreadsheet.worksheet(str(self.worksheet))
client.import_csv(spreadsheet.id, contents)
Note:
When I saw the document of gspread, it says as follows. So please be careful this.
This method removes all other worksheets and then entirely replaces the contents of the first worksheet.
This modified script supposes that you have already been able to get and put values for Google Spreadsheet using Sheets API with gspread.
Reference:
import_csv(file_id, data)

Related

How to write data in a specific tab of a spreadsheet with the Google Sheets API in Python?

I'm writing data in a Google Sheet using this function :
def Export_Data_To_Sheets(df):
response_date = service.spreadsheets.values().update(
spreadsheetId=SAMPLE_SPREADSHEET_ID_input,
valueInputOption='RAW',
range=SAMPLE_RANGE_NAME,
body=dict(
majorDimension='ROWS',
values=df.T.reset_index().T.values.tolist()[1:])
).execute()
print('Sheet successfully Updated')
It works well, but I have two tabs in my Google Sheet and I would like to choose in which one I want to write data. I don't know how can I do this.
In this point in the code:
range=SAMPLE_RANGE_NAME
You can replace this value with a sheet and cell reference, something like:
range="Sheet1!A1:D5"
Reference
Writing a Single Range

How can I Export Pandas DataFrame to Google Sheets using Python?

I managed to read data from a Google Sheet file using this method:
# ACCES GOOGLE SHEET
googleSheetId = 'myGoogleSheetId'
workSheetName = 'mySheetName'
URL = 'https://docs.google.com/spreadsheets/d/{0}/gviz/tq?tqx=out:csv&sheet={1}'.format(
googleSheetId,
workSheetName
)
df = pd.read_csv(URL)
However, after generating a pd.DataFrame that fetches info from the web using selenium, I need to append that data to the Google Sheet.
Question: Do you know a way to export that DataFrame to Google Sheets?
Yes, there is a module called "gspread". Just install it with pip and import it into your script.
Here you can find the documentation:
https://gspread.readthedocs.io/en/latest/
In particular their section on Examples of gspread with pandas.
worksheet.update([dataframe.columns.values.tolist()] + dataframe.values.tolist())
This might be a little late answer to the original author but will be of a help to others. Following is a utility function which can help write any python pandas dataframe to gsheet.
import pygsheets
def write_to_gsheet(service_file_path, spreadsheet_id, sheet_name, data_df):
"""
this function takes data_df and writes it under spreadsheet_id
and sheet_name using your credentials under service_file_path
"""
gc = pygsheets.authorize(service_file=service_file_path)
sh = gc.open_by_key(spreadsheet_id)
try:
sh.add_worksheet(sheet_name)
except:
pass
wks_write = sh.worksheet_by_title(sheet_name)
wks_write.clear('A1',None,'*')
wks_write.set_dataframe(data_df, (1,1), encoding='utf-8', fit=True)
wks_write.frozen_rows = 1
Steps to get service_file_path, spreadsheet_id, sheet_name:
Click Sheets API | Google Developers
Create new project under Dashboard (provide relevant project name and other required information)
Go to Credentials
Click on “Create Credentials” and Choose “Service Account”. Fill in all required information viz. Service account name, id, description et. al.
Go to Step 2 and 3 and Click on “Done”
Click on your service account and Go to “Keys”
Click on “Add Key”, Choose “Create New Key” and Select “Json”. Your Service Json File will be downloaded. Put this under your repo folder and path to this file is your service_file_path.
In that Json, “client_email” key can be found.
Create a new google spreadsheet. Note the url of the spreadsheet.
Provide an Editor access to the spreadsheet to "client_email" (step 8) and Keep this service json file while running your python code.
Note: add json file to .gitignore without fail.
From url (e.g. https://docs.google.com/spreadsheets/d/1E5gTTkuLTs4rhkZAB8vvGMx7MH008HjW7YOjIOvKYJ1/) extract part between /d/ and / (e.g. 1E5gTTkuLTs4rhkZAB8vvGMx7MH008HjW7YOjIOvKYJ1 in this case) which is your spreadsheet_id.
sheet_name is the name of the tab in google spreadsheet. By default it is "Sheet1" (unless you have modified it.
Google Sheets has a nice api you can use from python (see the docs here), which allows you to append single rows or entire batch updates to a Sheet.
Another way of doing it without that API would be to export the data to a csv file using the python csv library, and then you can easily import that csv file into a Google Sheet.

GSpread how to duplicate sheet

After googling and searching on Stackoveflow, I think I can't find a guide on how to duplicate existing sheet(existing Template sheet) and saving it into another sheet.
as per docs, there is duplicate_sheet but I can't manage to do a working example, anyone that can guide me with this?
import gspread
from gspread.models import Cell, Spreadsheet
scope = [
"https://www.googleapis.com/auth/spreadsheets.readonly",
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/drive.readonly",
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive",
]
json_key_absolute_path = "key.json"
credentials = ServiceAccountCredentials.from_json_keyfile_name(json_key_absolute_path, scope)
client = gspread.authorize(credentials)
spreadsheet_client = Spreadsheet(client)
spreadsheet_client.duplicate_sheet("18Qk5bzuA7JOBD8CTgwvKYRiMl_35it5AwcFG2Bi5npo", new_sheet_name="timcard2")
worksheet = client.open("timcard2")
worksheet.share("my_email#google.com", perm_type='user', role='writer')
You want to copy the source Spreadsheet as new Spreadsheet.
You want to achieve this using gspread with python.
You have already been able to get and put values for Google Spreadsheet using Sheets API.
If my understanding is correct, how about this answer?
Issue and solution:
It seems that duplicate_sheet method of gspread is used for copying a sheet in the source Spreadsheet to the same source Spreadsheet. Ref In order to copy the source Spreadsheet as new Spreadsheet, pleas use the method of copy() of Class Client.
Sample script:
Please modify your script as follows.
From:
client = gspread.authorize(credentials)
spreadsheet_client = Spreadsheet(client)
spreadsheet_client.duplicate_sheet("18Qk5bzuA7JOBD8CTgwvKYRiMl_35it5AwcFG2Bi5npo", new_sheet_name="timcard2")
worksheet = client.open("timcard2")
worksheet.share("my_email#google.com", perm_type='user', role='writer')
To:
client = gspread.authorize(credentials)
client.copy("18Qk5bzuA7JOBD8CTgwvKYRiMl_35it5AwcFG2Bi5npo", title="timcard2", copy_permissions=True)
worksheet = client.open("timcard2")
worksheet.share("my_email#google.com", perm_type='user', role='writer')
When you run the script, the Spreadsheet which has the spreadsheet ID of 18Qk5bzuA7JOBD8CTgwvKYRiMl_35it5AwcFG2Bi5npo is copied as the spreadsheet name of timcard2. And, the permission information of the source Spreadsheet is also copied.
Note:
In this case, when copy_permissions=True is used, the permission information is also copied. So although I'm not sure about your actual situation, it might not be required to use worksheet.share("my_email#google.com", perm_type='user', role='writer'). Please be careful this.
References:
duplicate_sheet
copy(file_id, title=None, copy_permissions=False)
Added:
You want to copy one of sheets in Google Spreadsheet.
I could understand like above. For this, the sample script is as follows.
Sample script:
client = gspread.authorize(credentials)
client.copy("18Qk5bzuA7JOBD8CTgwvKYRiMl_35it5AwcFG2Bi5npo", title="timcard2", copy_permissions=True)
ss = client.open("timcard2")
ss.share("my_email#google.com", perm_type='user', role='writer')
delete_sheets = ["Sheet2", "Sheet3", "Sheet4"] # Please set the sheet names you want to delete.
for s in delete_sheets:
ss.del_worksheet(ss.worksheet(s))
In this sample, the sheets of "Sheet2", "Sheet3", "Sheet4" are deleted from the copied Spreadsheet.
Reference:
del_worksheet(worksheet)

Getting gspread to update multiple spreadsheet files with the same data

As above I'm trying to update more than one sheet file with the same information using the sheet IDs as the identifier. I''ve attempted to achieve this with for loops with no success. Some of the basic code that I'm trying to achieve this with is:
conn = gspread.authorize(credentials)
sheets = ['sheetid1', 'sheetid2']
worksheet_list = conn.open_by_key(sheets).worksheet("Rack Layout")
worksheet_list.update_acell('Q1', 'some cell value')
So if I define 'sheets' as one sheetid the updates work fine, however if I define 'sheets' as more than one sheet I get the error. I know this is really basic and I think the issue is its trying to open the full list (i.e. both sheetids) on the same line, rather than saying 'run this line for one sheetID and then the next'. I think the way to achieve this is a for loop, but I've yet to get this to work with a for loop. I know this is a nube question, but I've been trying for a while now, and from my searching I haven't found any other forum posts about getting gspread to do this.
You have 2 Google Spreadsheets.
2 Google Spreadsheets have the sheet of "Rack Layout", respectively.
You want to put the value of "some cell value" to the cell "Q1" in the sheet of "Rack Layout" for each Spreadsheet.
You want to achieve this using gspread with python.
You have already been able to get and put values for Spreadsheet using Sheets API.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
In this modified script, the value is put to each Spreadsheet using the for loop.
Modified script:
conn = gspread.authorize(credentials)
sheets = ['sheetid1', 'sheetid2']
for sheet in sheets: # Added
worksheet_list = conn.open_by_key(sheet).worksheet("Rack Layout")
worksheet_list.update_acell('Q1', 'some cell value')
If I misunderstood your question and this was not the direction you want, I apologize.

how do i access a sheet name in gsp spreadsheet.worksheets()

I have google spreadsheet with different tabs. These hold quarterly metrics, e.g. 1Q14, 2Q14, etc.
I want to read these data and convert it to a Pandas DataFrame.
I managed to write code to open the spreadsheet with GSP.open
see first code snippet
Then I want to iterate over all sheets and extract their names from the list I obtain with:
sheets = spreadsheet.worksheets()
list of sheets returned
I want to get the first part, the name, not the id. I know I can obtain the full first entry in the list with sheet[0], but now, how do I get the name only, without the id?
How do I access the sheet name in that object that is returned? I can't find it - appreciate your help. Thank you, Marc
Just access the property title of the sheet, like this:
sheets = spreadsheet.worksheets()
for sheet in sheets:
sheet.title
Reference:
gspread: API Reference

Categories