vesszabo
vesszabo

Reputation: 441

How to delete rows in google spreadsheet using SHEET API v4 by Python?

My code is the following

def write_cells(spreadsheet_id, update_data):
updating = sheet_service.spreadsheets().values().\
        batchUpdate(spreadsheetId=spreadsheet_id, body=update_data)
updating.execute()

spreadsheet_data = [
    { 
        "deleteDimension": {
        "range": {
          "sheetId": sheet_id,
          "dimension": "ROWS",
          "startIndex": 5,
          "endIndex": 100
         }              
        }
       }
]    

update_spreadsheet_data = {
    'valueInputOption': 'USER_ENTERED',
    'data': spreadsheet_data
}

update_data = update_spreadsheet_data

write_cells(spreadsheet_id, update_data)

I have the following error message

HttpError                                 Traceback (most recent call last)
<ipython-input-64-0ba8756b8e85> in <module>()
----> 1 write_cells(spreadsheet_id, update_data)

2 frames

/usr/local/lib/python3.6/dist-packages/googleapiclient/http.py in execute(self, http, num_retries)
    838       callback(resp)
    839     if resp.status >= 300:
--> 840       raise HttpError(resp, content, uri=self.uri)
    841     return self.postproc(resp, content)
    842 

HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/1lAI8gp29luZDKAS1m3P62sq0kKCn8eaMUvO_M_J8meU/values:batchUpdate?alt=json returned "Invalid JSON payload received. Unknown name "delete_dimension" at 'data[0]': Cannot find field.">

I don't understand this: "Unknown name delete_dimension". I'm unable to resolve it. Any help is appreciated, thanks.

Upvotes: 2

Views: 8640

Answers (1)

Tanaike
Tanaike

Reputation: 201378

  • You want to delete rows using Sheets API with Python.

If my understanding is correct, how about this modification?

Modification points:

  • When delete rows in Spreadsheet, please use spreadsheets().batchUpdate().
  • I think that spreadsheet_data is correct.
  • In this case, please modify the request body to {"requests": spreadsheet_data}.

Modified script:

def write_cells(spreadsheet_id, update_data):
    # Modified
    updating = sheet_service.spreadsheets().batchUpdate(
        spreadsheetId=spreadsheet_id, body=update_data)
    updating.execute()


spreadsheet_data = [
    {
        "deleteDimension": {
            "range": {
                "sheetId": sheet_id,
                "dimension": "ROWS",
                "startIndex": 5,
                "endIndex": 100
            }
        }
    }
]

update_spreadsheet_data = {"requests": spreadsheet_data} # Modified

update_data = update_spreadsheet_data
write_cells(spreadsheet_id, update_data)

Note:

  • This modified script supposes that you have already been able to use Sheets API.

Reference:

If I misunderstood your question and that was not the result you want, I apologize.

Upvotes: 6

Related Questions