Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

openpyxl - change width of n columns

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.

like image 481
Kevin Crick Avatar asked Nov 09 '17 14:11

Kevin Crick


People also ask

How to set column width using openpyxl?

In order to change the column width size, you can make use of the column_dimesnsions method of the worksheet class.

How do you change the width of a column in Excel using Python?

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.

How to set the width of all columns in openpyxl?

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

How good is openpyxl for Excel?

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).

How do I set the width of column a to 50?

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")

How to customize font styles in cells in openpyxl?

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.


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
like image 147
Kevin Crick Avatar answered Sep 30 '22 23:09

Kevin Crick


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 = ?
like image 29
ryachza Avatar answered Sep 30 '22 23:09

ryachza