openpyxl - change width of n columns

Viewed 13004

I am trying to change the column width for n number of columns. I am able to do this for rows as per the below code.

rowheight = 2
while rowheight < 601:
    ws.row_dimensions[rowheight].height = 4
    rowheight += 1

The problem I have is that columns are in letters and not numbers.

2 Answers

As pointed out by ryachza the answer was to use an openpyxl utility, however the utility to use is get_column_letter and not column_index_from_string as I want to convert number to letter and not visa versa.

Here is the working code

from openpyxl.utils import get_column_letter

# Start changing width from column C onwards
column = 3
while column < 601:
    i = get_column_letter(column)
    ws.column_dimensions[i].width = 4
    column += 1

To get the column index, you should be able to use:

i = openpyxl.utils.column_index_from_string(?)

And then:

ws.column_dimensions[i].width = ?
Related