简体   繁体   中英

How do I append at the end of row in in google sheets using python

I am working on a project where i want to add values after the last row in google sheets, My code now i just overwriting the values if i rerun the code. For instance is i run the code twice i want to have double the values of whats inside the array "aoa" 7*2 rows.

from googleapiclient.discovery import build
from google.oauth2 import service_account


SERVICE_ACCOUNT_FILE = 'keys.json'
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

creds = None
creds = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1FL_OSVo82741728v_pMLlwiPx5fqS3WmoamM'

service = build('sheets', 'v4', credentials=creds)

#call the sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                            range="blad1").execute()
values = result.get('values', [])

aoa = [['value1', '1/111/2020', 5220], ['value1', '1/111/2020', 5220], ['value1', '1/111/2020', 5220],
       ['value1', '1/111/2020', 5220], ['value1', '1/111/2020', 5220], ['value1', '1/111/2020', 5220],
       ['value1', '1/111/2020', 5220]]


request = sheet.values.append().update(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                                range='blad1', valueInputOption='USER_ENTERED', body={'values':aoa}).execute()

print(values)

Replace:

request = sheet.values.append().update(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                                range='blad1', valueInputOption='USER_ENTERED', body={'values':aoa}).execute()

With:

request = sheet.values().append(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                                range='blad1', valueInputOption='USER_ENTERED', body={'values':aoa}).execute()

Example:

First Run:

在此处输入图像描述

Second Run:

在此处输入图像描述

Reference:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM