worksheet.ColumnDimensions auto_size not autosizing.

12,666 views
Skip to first unread message

Petro Verkhogliad

unread,
Apr 12, 2011, 1:39:36 PM4/12/11
to openpyxl-users
Hi,

i am trying to get the columns to auto size to the text. For this i
used the following code:

from openpyxl.workbook import Workbook
from openpyxl.worksheet import ColumnDimension


wb = Workbook()
ws = wb.create_sheet(0)

# fill in some data here

for ws_column in range(1,10):
col_letter = get_column_letter(ws_column)
ws.column_dimensions[col_letter].auto_size = True

save_workbook(wb, 'sizing.xlsx')

This doesn't seem to change anything in the sheet. The only way I
managed to change the width of the column is by setting doing this:

ws.column_dimensions[col_letter].width = 100 # or some other value

Could someone point out to me what I am missing?

Thank you,
Petro

Eric Gazoni

unread,
Apr 18, 2011, 9:36:10 AM4/18/11
to openpyx...@googlegroups.com
Hi Petro,
someone already had this issue and I think that Excel itself can't read
the auto-size parameter here, and just reads the statically defined widths.

I guess that when you do 'auto-size' in Excel, it just defined fixed
sizes behind the scenes and uses that.

Sorry for not having a better solution.

Cheers,
Eric

Le 12/04/11 19:39, Petro Verkhogliad a �crit :

Petro Verkhogliad

unread,
Apr 19, 2011, 2:39:13 PM4/19/11
to openpyx...@googlegroups.com
No problem. Explicitly setting the width of the column works well enough.


It also occurred to me that if a user double-clicks the column Excel will expand the column to the size of the longest cell. Now if someone changes the one of the values a something that is longer than the previously longest value, Excel does not auto-size the column, ie you have to double-click the column boundary again. Since there is no expectation from on the user's part of real auto-sizing behavoir, explicit width works fine.

Thanks again for an awesome library.

Petro

webto...@gmail.com

unread,
Sep 24, 2015, 11:41:41 PM9/24/15
to openpyxl-users
OP, please do not post broken code
Reply all
Reply to author
Forward
0 new messages