Python insert to Google sheet with auto detect last row
Sat Jun 24 2023 12:47:06 GMT+0000 (Coordinated Universal Time)
Saved by
@yogitaunay
#python
def ipt_sheet():
credentials = service_account.Credentials.from_service_account_file(
'./p-gsheet.json')
scoped_credentials = credentials.with_scopes(
['https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'])
# Authorize the client
client = gspread.authorize(scoped_credentials)
# Open the Google Sheet by its title
sheet = client.open('NOTIF EXPIRED')
# Select the specific worksheet within the sheet
worksheet = sheet.worksheet('Sheet1')
# Define the data to insert
data = [[datetime.today().strftime('%m-%d-%Y'), 'Value 3', 'Value 2', 'Value 3', 'Value 4', 'val6']]
# Specify the column to insert the data
column_index = 2 # Example: Insert in column B
# Find the last row with data in the specified column
last_row = len(worksheet.col_values(2)) + 1
# Insert the data into the specified column and row
worksheet.insert_rows(data, row=last_row)
print('Data inserted successfully!')
content_copyCOPY
Comments