Home > Blockchain >  How to append a new worksheet and upload a local CSV in gspread
How to append a new worksheet and upload a local CSV in gspread

Time:08-17

I checked the docs of gspread but couldn't find out a way to APPEND a new local csv into a worksheet into a preexisting sheet.

As far as I see the import function just cleans and uploads into the first page. But I want to create a new work sheet in the same sheet and appends a csv every day.

Thank you

CodePudding user response:

I believe your goal is as follows.

  • You want to upload CSV data to Google Spreadsheet.
  • When the CSV data is uploaded, you want to insert a new sheet to the existing Spreadsheet and want to put the CSV data to the inserted new sheet.
  • You want to achieve this using gspread for python.

In this case, how about the following sample script?

Sample script:

import gspread


client = gspread.oauth(
    credentials_filename="###", # Please set your file.
    authorized_user_filename="###", # Please set your file.
)

csvFilePath = "./sample.csv"  # Please set CSV file path.
newSheetName = "sample new sheet name"  # Please set the new sheet name.
spreadsheetTitle = "sample Spreadsheet"  # Please set the filename of Spreadsheet.

spreadsheet = client.open(spreadsheetTitle)
sheetId = spreadsheet.add_worksheet(newSheetName, 1, 1).id
with open(csvFilePath, "r") as f:
    csvContents = f.read()
body = {
    "requests": [
        {
            "pasteData": {
                "coordinate": {
                    "sheetId": sheetId,
                },
                "data": csvContents,
                "type": "PASTE_NORMAL",
                "delimiter": ",",
            }
        },
    ]
}
spreadsheet.batch_update(body)
  • When this script is run, a new sheet is inserted into the Spreadsheet. And, the CSV data is uploaded to the new sheet.

Reference:

  • Related