Search code examples
pythongoogle-sheets-apigoogle-api-python-client

How to use FindReplace for specify sheetname by Google API V4 Python


I would like to use Python to update the filename and spreadsheet ID saved in a Google Sheet when I upload files to my Drive according to the sheetName in the Sheet, and I want to delete or replace a row with a duplicate name when I upload my files (so that the newest file ID is updated with same date).

I have been using batchUpdate, but I can only replace the same column but not the same row, and only in the first sheet of my spreadsheet.

Here's the script:

#file_name and file_ID: obtain when upload the files,
def update(file_name, file_ID):

    range_name = file_name + "!A:B"

    requests = []
    requests.append([{
        "findReplace": {
            "find": Date,
            "replacement": FileID,
            "matchCase": True,
            "matchEntireCell": True,
            "searchByRegex": True,
            "range": {
                "sheetId": 0,
                "startColumnIndex": 0,
                "endColumnIndex": 1
            },
        }
    }])

    body = {"requests": [requests]}
    response = service.spreadsheets().batchUpdate(
        spreadsheetId=spreadsheet_id, body=body).execute()
    pprint(response)

Is there any way I can use to find if the name is column A in the "filetype1" sheet (need match the Sheet Name to determine under which sheet first), then replace the ID in column B?

Example sheet


Solution

  • I comprehend that you have a table where you want to search for a Date and change its ID value of the same row. If understood it correctly, you would need to use Values.get() and Values.update() methods.

    First you will need to use get to read the full table. Parse it with Python and substitute the appropriate values. After that operation you can upload the full table as an update request. Please, don't hesitate to ask me any follow-up questions.