pythongoogle-sheetsgspreadgspread-formatting

Python gspread formatting - Set vertical alignment to middle for range of cells


I'm trying to format some cells of a google sheet. Since I'm using new line characters in certain cells of the first row, I noticed vertical alignment is automatically set to bottom, whereas I would like to have a centered vertical alignment for a range of cells in this first row.

I've omitted quite a few columns from the following code block, as I have over 25:

import gspread
from google.oauth2.service_account import Credentials

scopes = ["https://www.googleapis.com/auth/spreadsheets"]
creds = Credentials.from_service_account_file("credentials.json", scopes=scopes)
client = gspread.authorize(creds)

sheet_id = "url"
workbook = client.open_by_key(sheet_id)

worksheet_list = map(lambda x: x.title, workbook.worksheets())
new_worksheet_name = "template"

# check if new sheet exists already
if new_worksheet_name in worksheet_list:
    sheet = workbook.worksheet(new_worksheet_name)
else:
    sheet = workbook.add_worksheet(new_worksheet_name, rows=91, cols=30)

values = [
    ["Data\nYYYY/MM/DD", "Totale\ninizio giorno", "Totale\ndopo refresh", "Set giornaliero", "Serie\ngiornaliera"],
]

sheet.clear()

sheet.update(values, f"A1:Z{len(values)}")

sheet.format("A1:Z1", {"textFormat": {"bold": True}})

I tried (hoping it would work the same way as bold) sheet.format("A1:Z1", {"verticalAlignment": {"MIDDLE": True}}) but I get the following traceback:

  File "C:path", line 41, in <module>
    sheet.format("A1:Z1", {"verticalAlignment": {"MIDDLE": True}})
  File "C:path\.venv\Lib\site-packages\gspread\worksheet.py", line 1479, in format
    return self.batch_format(formats)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:path\.venv\Lib\site-packages\gspread\worksheet.py", line 1430, in batch_format
    return self.client.batch_update(self.spreadsheet_id, body)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:path\.venv\Lib\site-packages\gspread\http_client.py", line 134, in batch_update
    r = self.request("post", SPREADSHEET_BATCH_UPDATE_URL % id, json=body)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:path\.venv\Lib\site-packages\gspread\http_client.py", line 123, in request
    raise APIError(response)
gspread.exceptions.APIError: {'code': 400, 'message': "Invalid value at 'requests[0].repeat_cell.cell.user_entered_format' (vertical_alignment), Starting an object on a scalar field", 'status': 'INVALID_ARGUMENT', 'details': [{'@type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'requests[0].repeat_cell.cell.user_entered_format', 'description': "Invalid value at 'requests[0].repeat_cell.cell.user_entered_format' (vertical_alignment), Starting an object on a scalar field"}]}]}

Solution

  • For vertical alignment, you don't use a boolean. You should use a string specifying the alignment type:

    import gspread
    from google.oauth2.service_account import Credentials
    scopes = ["https://www.googleapis.com/auth/spreadsheets"]
    creds = Credentials.from_service_account_file('your_credentials_file.json', scopes=scopes)
    client = gspread.authorize(creds)
    sheet_id = "your_sheet_id"
    workbook = client.open_by_key(sheet_id)
    new_worksheet_name = "template"
    worksheet_list = [ws.title for ws in workbook.worksheets()]
    if new_worksheet_name in worksheet_list:
        sheet = workbook.worksheet(new_worksheet_name)
    else:
        sheet = workbook.add_worksheet(new_worksheet_name, rows=91, cols=30)
    values = [["Data\nYYYY/MM.DD", "Totale\ninizio giorno", "Set giornaliero", "Serie\ngiornaliera"],]
    sheet.clear()
    sheet.update("A1:Z1", values)
    sheet.format("A1:Z1", {"textFormat": {"bold": True}})
    sheet.format("A1:Z1", {"verticalAlignment": "MIDDLE"})