Search code examples
pythongoogle-sheetsgspread

Delete (remove) column in google sheet over gspread Python like sheet.delete_row


Is there a method like worksheet.delete_row in gspread google-sheet? I tried:

delete = sheet.range('A1:A1000')
        for cell in delete:
            cell.value = ""
            sheet.update_cells(delete)

but that only delete all values, not column. Can anybode help me?


Solution

  • Answer:

    There is no method in gspread to delete an entire column, like Workbook.delete_row, however you can do this with a batch update.

    Code sample:

    spreadsheetId = "your-spreadsheet-id"
    sheetId = "id-of-sheet-to-delete-column-from"
    
    sh = client.open_by_key(spreadsheetId)
    
    request = {
        "requests": [
            {
                "deleteDimension": {
                    "range": {
                        "sheetId": sheetId,
                        "dimension": "COLUMNS",
                        "startIndex": 0,
                        "endIndex": 1
                    }
                }
            }
        ]
    }
    result = sh.batch_update(request)
    

    This sample will delete column A, but make sure to change the startIndex and endIndex to be of the column range you wish to delete.

    Edit: If you do not know the sheetId of a given sheet, you can get it using the following:

    sheetName = "theSheetName"
    sheetId = sh.worksheet(sheetName)._properties["sheetId"]
    

    Note that this is not needed for the original sheet of a Spreadsheet, as this will always be 0.

    References:


    Update 2020-04-15:

    This script was merged with gspread master today from pull request #759 as method delete_column().

    The method will be available in the next release v3.5.0.

    A method for delete_columns() was also added as a parallel method to the existing delete_rows() from pull request #761.