Case: My script returns a data frame that needs has to be appended to an existing google spreadsheet as new rows of data.As of now, I\'m appending a data frame as multiple s
I came up with the following solution. It does not overwrite current data but just appends entire pandas DataFrame df
to the end of Sheet with name sheet
in the Spreadsheet with the name spread_sheet
.
import gspread
from google.auth.transport.requests import AuthorizedSession
from oauth2client.service_account import ServiceAccountCredentials
def append_df_to_gs(df, spread_sheet:str, sheet_name:str):
scopes = [
'https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive',
]
credentials = ServiceAccountCredentials.from_json_keyfile_name(
path_to_credentials,
scopes=scopes
)
gsc = gspread.authorize(credentials)
sheet = gsc.open(spread_sheet)
params = {'valueInputOption': 'USER_ENTERED'}
body = {'values': df.values.tolist()}
sheet.values_append(f'{sheet_name:str}!A1:G1', params, body)
For params valueInputOption
please consult this. I used USER_ENTERED
here as I needed some formulas to be valid once I append the data to Google Sheets.