Search code examples
pythongoogle-sheetsgoogle-sheets-apigspread

GSpread appending to specific column


I'm currently using gspread's "append_row" function to append a string of text to the first column in the spreadsheet. However, I'd like to append the text to a different column than column one.

`

from oauth2client.service_account import ServiceAccountCredentials
import gspread

scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive',
         'https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/spreadsheets']
creds = ServiceAccountCredentials.from_json_keyfile_name('creds.json', scope)
client = gspread.authorize(creds)

sheet = client.open_by_url("url_to_spreadsheet").worksheet("Sheet1")


sheet.append_row(["some text"])



`

I tried using sheet.append_row(["some text"]) to append text to a column in the spreadsheet, but it only appends to column one.


Solution

  • I believe your goal is as follows.

    • You want to put the value of "some text" to the specific column of the next row of the last row using gspread for python.

    When append_row is used to an empty sheet, range can be used. But, when the values are existing in the sheet, even when range is used, the values cannot be put into the expected column. I'm not sure whether this is the current specification or a bug. So, in this case, how about the following modification?

    From:

    sheet.append_row(["some text"])
    

    To:

    column = 3  # Please set the column number you want to put the value. 3 means column "C".
    last_row = len(sheet.get_all_values())
    sheet.update_cell(last_row + 1, column, "some text")
    

    Or, when you want to use a list, please use the following sample.

    column = 3  # Please set the column number you want to put the value. 3 means column "C".
    last_row = len(sheet.get_all_values())
    dst_range = gspread.utils.rowcol_to_a1(last_row + 1, column)
    sheet.update(dst_range, [["some text"]], value_input_option="USER_ENTERED")
    

    References: