Iddos
Iddos

Reputation: 127

python gspread - How to delete/remove column in google-sheet-API

I'm logging data from a CSV file to google sheet using gspread in python with values_update().

I then use gspread-formatting to create a background color. Since I haven’t found a way to format colors from the CSV, my script reads the data in column C where I store the color I want to use.

After creating the background color I want to delete column C including the header (row 1)

What is the best way to delete or remove an entire column? Alternatively, if there is a way to log the background color straight from the CSV file that will be even better.

projectSheet.values_update(
worksheet, params={'valueInputOption': 'USER_ENTERED'},
body={'values': list(csv.reader(open(csvName)))}
)

blue = [cell.row for cell in worksheet.findall('Blue')]
for i in blue:
    fmtBlue = cellFormat(
    backgroundColor=color(0.5, 0.5, 1),
    textFormat=textFormat(bold=False, foregroundColor=color(0, 0, 0)),
    horizontalAlignment='CENTER'
    )
    rows = f'A{i}:J{i}'
    format_cell_range(worksheet, rows, fmtBlue)

worksheet.delete_column('C')???

Upvotes: 2

Views: 2767

Answers (1)

Tanaike
Tanaike

Reputation: 201553

  • You want to delete the columns using gspread.
  • You have already been able to put and get values using Sheets API.
  • Your question is as follows.
    • What is the best way to delete or remove an entire column?
    • If there is a way to log the background color straight from the CSV file that will be even better.

If my understanding is correct, how about this sample script? Unfortunately, I cannot understand about If there is a way to log the background color straight from the CSV file.. So I cannot answer it. But I can answer about What is the best way to delete or remove an entire column?. So here, I would like to propose the method for deleting the columns using gspread.

It seems that there is no method of delete_column in gspread. So in this case, I would like to propose to use batch_update() of gspread. Please think of this as just one of several answers.

Sample script:

spreadsheetId = "###"  # Please set Spreadsheet ID.
sheetName = "###"  # Please set sheet name which has the columns you want to delete.

spreadsheet = client.open_by_key(spreadsheetId)
sheetId = spreadsheet.worksheet(sheetName)._properties['sheetId']
body = {
    "requests": [
        {
            "deleteDimension": {
                "range": {
                    "sheetId": sheetId,
                    "dimension": "COLUMNS",
                    "startIndex": 2,
                    "endIndex": 3
                }
            }
        }
    ]
}
res = spreadsheet.batch_update(body)
print(res)
  • Please set the range as the GridRange.
  • In above script, the column "C" is deleted.

References:

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

Upvotes: 3

Related Questions