Getting gspread to update multiple spreadsheet files with the same data - python

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.

Related

Refresh single worksheet (excel) in workbook using xlwings

I looked around a bit but could not find an answer. I found RefreshAll() which is not what I want to do.
Say I have a workbook named "DATA" with following sheets, "Forecast Temps", "Actual Temps", "Table", "Summary".
Now imagine that Forecast Temps sheet has a time series function that grabs data from NWS. This worksheet needs to be refreshed and then temps added into specified column in worksheet "Table". After this, Sheet Summary can be refreshed to determine new high and lows for that day.
Yes - I could run RefreshAll() at each step, but this seems redundant and would take the script longer to run. I was wondering if there was a way to refresh a single sheet w/ xlwings.
I also know you can do it in VBA, but my plan is to write a python script and then create a Sub where I call RunPython ("ScriptName").
Would I be able to do something like:
import xlwings as xw
wb = xw.Book("path")
forecast_temps = wb.sheet[0]
summary = wb.sheet[1]
forecast_temps.refresh() #do not know the correct func here (if there is one)?
I think RefreshAll() is not part of xlwings API. You may call the Excel API like this: wb.api.RefreshAll().
If you know how to do it in VBA, the same will probably work in xlwings using .api. I think you will have some kind of workbook connection. wb.api.Connections should return a list of all workbook connections. From there you can go on with the WorkbookConnection-Objects, which have a Refresh() method.

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

Using gspread to extract sheet ID

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)

gspread - get_all_values() returns an empty list

If I call a sheet by name, get_all_values function will always give me an empty list for a sheet that is definitely not empty.
import gspread
sheet = workbook.worksheet(sheet_name)
all_rows_list = sheet.get_all_values()
The only time get_all_values seems to return like it should is if I do the following:
all_rows_list = workbook.sheet1.get_all_values()
But the above works just for the first sheet and for no other, which is kind of useless for a workbook with more sheets.
What always works is reading row by row like
one_row_list = sheet.row_values(1) # first row
But the problem is that I'm trying to read a relatively big workbook with lots of sheets to figure out where I'm supposed to start writing, and it looks like reading row by row triggers "RESOURCES EXHAUSTED" error very fast.
So, am I doing something wrong or is get_all_values broken in gspread?
EDIT:
Added a screenshot.
gspread doesn't work well with sheets with names that could be confused as a cell reference in the A1 notation (like X101 and AT8 in your case).
https://github.com/burnash/gspread/issues/554 is an older issue that describes the underlying problem (the symptoms in that issue are different, but I'm pretty sure the root problem is the same).
I'll copy the workaround with providing a range, that you've discovered yourself:
ws.range("A1:C"+str(end_row)) That end_row is usually row_count of the sheet.

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