django-commons / drf-excel

An XLSX spreadsheet renderer for Django REST Framework.
BSD 3-Clause "New" or "Revised" License
217 stars 40 forks source link

Column Width #70

Open fjbardelli opened 1 year ago

fjbardelli commented 1 year ago

Hello, thanks for the library, it is a great contribution and very useful.

Is it possible to set the column width, automatic for each column take the minimum possible width?

Thanks

FlipperPA commented 1 year ago

Howdy @fjbardelli! Thanks for writing.

This is a tough nut to crack, because of different font sizes across Mac, PC, and even versions of Excel. Users can set up a different default font, and also specify different fonts for other cells, which changes the math used to calculate the "automatic" feature.

We use OpenPyXL under the hood, and you can see from this thread on Stack Overflow, that there are a bunch of hacks that are possible, but not a one-size-fits-all solution. That's why we've stayed away from implementing this.

This was the state of play from my memory of a few years ago, so if things have changed or anyone has found a good solution and wants to issue a PR, it is a feature I'd like to have as well!

This page seems to state that recent versions support auto_size as a worksheet dimension, but I'm not sure it would work for a column.

Maybe something like this would work?

import openpyxl
from openpyxl.utils import get_column_letter

wb = openpyxl.load_workbook("Example.xslx")
ws = wb["Sheet1"]
for i in range(1, ws.max_column + 1):
    ws.column_dimensions[get_column_letter(i)].bestFit = True
    ws.column_dimensions[get_column_letter(i)].auto_size = True