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

核能气质少年 提交于 2021-01-28 09:41:49

问题


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?


回答1:


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.

I hope this is helpful to you!

References:

  • Method: spreadsheets.batchUpdate | Sheets API | Google Developers
  • API References - gspread 3.4.0 documentation - batch_update(body)

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.



来源:https://stackoverflow.com/questions/61213417/delete-remove-column-in-google-sheet-over-gspread-python-like-sheet-delete-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!