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.
In order to change the column width size, you can make use of the column_dimesnsions method of the worksheet class.
Setting the Column Width Set the width of a column by calling the Cells collection's setColumnWidth method. The setColumnWidth method takes the following parameters: Column index, the index of the column that you're changing the width of. Column width, the desired column width.
Even more pythonic way to set the width of all columns that works at least in openpyxl version 2.4.0: for column_cells in worksheet.columns: length = max (len (as_text (cell.value)) for cell in column_cells) worksheet.column_dimensions
I am using OpenPyXL to generate some Excel downloads from one of my Django apps. In general, I'm pretty happy with how it works. Setting a column width is easy. Figuring out how to do that from the documentation is hard. So here it is, just in case someone else needs to know (or me a week from now when I forget).
Assuming you have OpenPyXL installed, to set the width of Column A to 50: from openpyxl import Workbook wb = Workbook worksheet = wb. active worksheet. column_dimensions ['A']. width = 50 wb. save (filename = "col_width.xlsx")
To customize font styles in cells, important, import the Font () function from the openpyxl.styles module. Code #4 : Program to set the font of the text. Writing code in comment? Please use ide.geeksforgeeks.org , generate link and share the link here.
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 = ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With