jainraje
jainraje

Reputation: 1

reading/writing data frame to google sheets using pygsheets

What is the correct program flow to write different sized data frame to the same worksheet but ensure only the most recent data values written are visible?

Here was my original sequence:

gc = pygsheets.authorize(outh_file=oauth_file)
sh = gc.open(sheet_name)
wks = sh.worksheet_by_title(wks_name)
wks.set_dataframe(df, (1, 1))

Problem with above sequence is if 1st write was 3800 rows x 12 cols and 2nd write was 2400 rows x 12 cols the wks would still show data from the prior write for rows above 2400.

My 2nd solution (basically a hack just to get it to work for me):

gc = pygsheets.authorize(outh_file=oauth_file)
sh = gc.open(spreadsheet_name)
wks = sh.worksheet_by_title(sheet_name)
sh.del_worksheet(wks)
sh.add_worksheet(sheet_name, rows=len(df) + 1, cols=len(df.columns))
wks = sh.worksheet_by_title(sheet_name)
wks.set_dataframe(df, (1, 1))

The above sequence basically does what I want but I do not like having to delete the wks (I lose all my manual formatting). I know there must be a correct way to accomplish but I do not know the pygsheets API very well.

Will a more advanced pygsheet users please advise proper program flow and methods to use?

TIA, --Rj

Upvotes: 0

Views: 8865

Answers (1)

Nithin
Nithin

Reputation: 5840

fit=True will basically resize the sheet to fit you data frame. so if you wanna keep the sheet at same size, you can clear the sheet before next write. it wold be easier than your second solution. Also if you just wanna clear the range you had written earlier, you can pass a range to clear function.

wks.set_dataframe(df, (1, 1))
wks.clear()
wks.set_dataframe(df, (1, 1))

Upvotes: 1

Related Questions