且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过gspread Python(例如sheet.delete_row)在Google工作表中删除(删除)列

更新时间:2023-12-05 19:17:10

答案:

gspread 中没有方法可以删除整个列,例如 Workbook.delete_row ,但是您可以通过批量更新来做到这一点.

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.

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)

此示例将删除列A,但请确保将 startIndex endIndex 更改为您要删除的列范围.

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.

修改:如果您不知道给定工作表的 sheetId ,则可以使用以下方法获取它:

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"]

请注意,电子表格的原始表不需要这样做,因为 总是 0 .

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

希望对您有帮助!

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

此脚本今天从拉请求#中与 gspread master合并.759 作为方法 delete_column().

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

该方法将在下一个版本 v3.5.0 中提供.

用于 delete_columns()的方法也作为并行方法从

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