Append a list in Google Sheet from Python

Deadly 提交于 2021-02-07 13:21:34

问题


I have a list in Python which I simply want to write (append) in the first column row-by-row in a Google Sheet. I'm done with all the initial authentication part, and here's the code:

credentials = GoogleCredentials.get_application_default()
service = build('sheets', 'v4', credentials=credentials)

I do not have any clue as to how I could possibly do this in an easy way.


回答1:


How about this sample script? This sample appends list to column A. The list as data is 2 dimensional array. Please be careful for this. In order to use this script, please enable Sheet API v4 at API console.

Sample script :

credentials = GoogleCredentials.get_application_default()
service = build('sheets', 'v4', credentials=credentials)

list = [["valuea1"], ["valuea2"], ["valuea3"]]
resource = {
  "majorDimension": "ROWS",
  "values": list
}
spreadsheetId = "### spreadsheet ID"
range = "Sheet1!A:A";
service.spreadsheets().values().append(
  spreadsheetId=spreadsheetId,
  range=range,
  body=resource,
  valueInputOption="USER_ENTERED"
).execute()

You can see the detail information of spreadsheets.values.append at here.

If this sample was not useful for you, I'm sorry.




回答2:


You could try something like this:

credentials = GoogleCredentials.get_application_default()
service = build('sheets', 'v4', credentials=credentials)
spreadsheet_id = "give the spreadsheet ID of the sheet you want to append to"
range_name = "specify the range you are looking at eg: A1:B1"

values = [
   [list of cell values per row]
   [additional rows of data]
]

body = {
'values': values
}

result = service.spreadsheets().values().update(
    spreadsheetId=spreadsheet_id, range=range_name,
    valueInputOption=value_input_option, body=body).execute()

from the docs:

Updates require a valid ValueInputOption parameter (for singular updates, this is a required query parameter; for batch updates, this parameter is required in the request body). The ValueInputOption controls whether input strings are parsed or not, as described in the following table:

RAW The input is not parsed and is simply inserted as a string, so the

input "=1+2" places the string "=1+2" in the cell, not a formula. (Non-string values like booleans or numbers are always handled as RAW.)

USER_ENTERED The input is parsed exactly as if it were entered

into the Google Sheets UI, so "Mar 1 2016" becomes a date, and "=1+2" becomes a formula. Formats may also be inferred, so "$100.15" becomes a number with currency formatting.




回答3:


Based on Google's official quickstart + @Tanaike's answer, I suggest the following example on how to append rows to a Sheet document:


Take the spreadsheet id from the URL:

Script:

import os
import pickle
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

SHEETS_READ_WRITE_SCOPE = 'https://www.googleapis.com/auth/spreadsheets'
SCOPES = [SHEETS_READ_WRITE_SCOPE]


def main():
    spreadsheet_id = '1TfWKWaWypbq7wc4gbe2eavRBjzuOcpAD028CH4esgKw'  # this is part of the url of google
    rows = [
        ["Hello World", "שלום עולם ינעל העולם", ":)"],
        ["Hello"],
        ["World"]
    ]

    # -----------

    credentials = get_or_create_credentials(scopes=SCOPES)  # or use GoogleCredentials.get_application_default()
    service = build('sheets', 'v4', credentials=credentials)
    service.spreadsheets().values().append(
        spreadsheetId=spreadsheet_id,
        range="Sheet1!A:Z",
        body={
            "majorDimension": "ROWS",
            "values": rows
        },
        valueInputOption="USER_ENTERED"
    ).execute()


# Source: https://developers.google.com/sheets/api/quickstart/python
def get_or_create_credentials(scopes):
    credentials = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            credentials = pickle.load(token)
    if not credentials or not credentials.valid:
        if credentials and credentials.expired and credentials.refresh_token:
            credentials.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('credentials.json', scopes)
            credentials = flow.run_local_server(port=0)
        with open('token.pickle', 'wb') as token:
            pickle.dump(credentials, token)
    return credentials


if __name__ == '__main__':
    main()

  • Remember to change - spreadsheet_id = "<your spreadsheet document id>"

Result:
This is how it looks like if you'll run the script multiple consecutive times

💡 Do follow Google's official quickstart and grant yourself API permissions + install these packages:

pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib 


来源:https://stackoverflow.com/questions/46274040/append-a-list-in-google-sheet-from-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!