1

I'm working on my Python script and right now my script can import csv to spreadsheet, but I have to modify it to replace or delete the old spreadsheet that already imported and update it to the latest csv, since currently my script only working in upload and normal paste of data on csv file. What do I need to modify my script?

My script


def export_csv(o_csv, sheet_id):
    with open(o_csv, 'r') as csv_file:

       csvContents = csv_file.read()
    body = {
        'requests': [{
            'pasteData': {
                "coordinate": {
                    "sheetId": sheet_id,
                    "rowIndex": "0",
                    "columnIndex": "0",
                },
                "data": csvContents,
                "type": 'PASTE_NORMAL',
                "delimiter": ',',
            }
        }]
    }
Nimantha
  • 6,405
  • 6
  • 28
  • 69
rodskies
  • 119
  • 1
  • 11
  • The easiest way to update it is going to be to delete the old file and create a new one. Other wise your going to have to have your script go though each line and compare them using the google sheets api. This is a lot of work and prone to errors. – Linda Lawton - DaImTo May 25 '22 at 13:00

1 Answers1

0

I believe your goal is as follows.

  • After the sheet of sheet_id is cleared, you want to put the CSV data to the sheet of sheet_id.
  • You want to achieve this using gspread for python.

In this case, how about the following modification?

From:

body = {
    'requests': [{
        'pasteData': {
            "coordinate": {
                "sheetId": sheet_id,
                "rowIndex": "0",
                "columnIndex": "0",
            },
            "data": csvContents,
            "type": 'PASTE_NORMAL',
            "delimiter": ',',
        }
    }]
}

To:

body = {
    "requests": [
        {"updateCells": {"range": {"sheetId": sheet_id}, "fields": "*"}}, # Added
        {
            "pasteData": {
                "coordinate": {
                    "sheetId": sheet_id,
                    "rowIndex": "0",
                    "columnIndex": "0",
                },
                "data": csvContents,
                "type": "PASTE_NORMAL",
                "delimiter": ",",
            }
        },
    ]
}
  • In this case, by adding one request to your request body, the sheet of sheet_id is cleared. And, after the sheet was cleared, the CSV data is put. By this, this request can be done by one API call.
  • In this case, fields use *. If you want to control the clear contents, please modify this.

References:

Tanaike
  • 181,128
  • 11
  • 97
  • 165