I have filled a worksheet with some data and I'm trying to make column widths to assume their best fit, as in here. Basically the kind of autofit that happens when you double-click the column width adjustment separator.
This is my minimal example, which, as far as my understanding of openpyxl
documentation goes, should work:
import openpyxl
from typing import NoReturn
def columns_best_fit(ws: openpyxl.worksheet.worksheet.Worksheet) -> NoReturn:
"""
Make all columns best fit
"""
column_letters = tuple(openpyxl.utils.get_column_letter(col_number + 1) for col_number in range(ws.max_column))
for column_letter in column_letters:
dim = openpyxl.worksheet.dimensions.ColumnDimension(ws, index=column_letter, bestFit=True, customWidth=True)
ws.column_dimensions[column_letter] = dim
wb = openpyxl.Workbook()
ws = wb.active
ws.append(("Long Column Header 1", "Even Longer Column Header 2"))
ws.append(("some data", "more data"))
columns_best_fit(ws)
wb.save("column_width_test.xlsx")
However, when I open the resulting file, the columns are just slightly wider, but certainly not best fit.
bestWidth=True
has no effect. β JanethWONTFIX
β Drain