Search code examples
pythongoogle-sheets-apigspread

python gspread import csv to specific work sheet


Is there a straight forward way to import data from a CSV file to a specific work sheet using gspread? The default is always sheet1, as mentioned in the documentations.

If there is none, what would be the most economical approach regarding "google API Write Requests"?


Solution

    • You want to put the CSV data from a file to the specific sheet in a Spreadsheet.
    • You want to achieve this using gspread.
    • You have already been able to put and get values for Spreadsheet using gspread.

    If my understanding is correct, how about this sample script? In this sample script, I used values_update(). Please think of this as just one of several answers.

    Sample script:

    client = gspread.authorize(credentials)
    spreadsheetId = '###'  # Please set spreadsheet ID.
    sheetName = 'Sheet2'  # Please set sheet name you want to put the CSV data.
    csvFile = 'sample.csv'  # Please set the filename and path of csv file.
    
    sh = client.open_by_key(spreadsheetId)
    sh.values_update(
        sheetName,
        params={'valueInputOption': 'USER_ENTERED'},
        body={'values': list(csv.reader(open(csvFile)))}
    )
    

    Note:

    • Please import csv like import csv.
    • This sample script supposes that the shee of "Sheet2" is existing in the Spreadsheet.
    • In this sample script, the CSV data is put from the cell "A1" of "Sheet2" in the Spreadsheet.

    Reference:

    If I misunderstood your question and this was not the direction you want, I apologize.