Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Key Error while setting width of column - OpenPyXL

I am getting an error when setting the width of a column

workbook = Workbook()

#Add a sheet
worksheet = workbook.active

worksheet.column_dimensions["C"].width = 60.0

Here is the error.

KeyError: 'C'
like image 933
Umair Ayub Avatar asked Nov 30 '25 06:11

Umair Ayub


1 Answers

There is no column "C" to resize.

Verify this with:

worksheet.columns

If you first create a cell in column C:

import openpyxl
wb = openpyxl.Workbook()
ws = wb.active
_cell = ws.cell(row=1, column=3)

You can then resize it, and not throw a KeyError:

ws.column_dimensions["C"].width = 60.0
like image 139
Jeffrey Swan Avatar answered Dec 01 '25 18:12

Jeffrey Swan