1

Is there way to auto-size (auto-fit) the width based on cell contents for the entire worksheet.

sheet.column_dimensions['A'].width=number

I am not looking for the above, for which you have to specify the column. Is there a way to set it up with "openpyxl"?

Jongware
  • 22,200
  • 8
  • 54
  • 100
Jay
  • 17
  • 2
  • 1
    ***"way to auto-size (auto-fit)"***: Not implemented in `openpyxl`. Relevant [`[python][openpyxl] column width`](https://stackoverflow.com/search?q=isanswered%3Ayes+is%3Aquestion+%5Bpython%5D%5Bopenpyxl%5D+column+width) – stovfl Feb 12 '20 at 08:50
  • You indeed could have found this yourself. It is a known – and *closed* – issue: https://bitbucket.org/openpyxl/openpyxl/issues/1275/auto_size-and-bestfit-not-working – Jongware Feb 12 '20 at 18:39
  • 1
    https://stackoverflow.com/questions/13197574/openpyxl-adjust-column-width-size – Johnny Metz Feb 12 '20 at 22:22

2 Answers2

0

After many hours of research finally, I found it. This code decides the best fit for the columns. I feel this answers you question because you are using the word Auto-fit

NOTE : In the below code, sheet is the worksheet name. Usually in the documentation, we can see it as ws. Please don't forget to change the worksheet name.

# Imorting the necessary modules
try:
        from openpyxl.cell import get_column_letter
except ImportError:
        from openpyxl.utils import get_column_letter
        from openpyxl.utils import column_index_from_string
from openpyxl import load_workbook
import openpyxl
from openpyxl import Workbook



for column_cells in sheet.columns:
    new_column_length = max(len(str(cell.value)) for cell in column_cells)
    new_column_letter = (get_column_letter(column_cells[0].column))
    if new_column_length > 0:
        sheet.column_dimensions[new_column_letter].width = new_column_length*1.23

UPDATE : This code doesn't work for all, but don't hesitate to try it

Mounesh
  • 561
  • 5
  • 18
-3

If you simply want to set the width to some "number", just loop over it (to the max column), If you need to set the width for each column specifically tailored to the contents of that(!) column, I think that is not possible with openpyxl (sadly).

TylerH
  • 20,799
  • 66
  • 75
  • 101
rt87
  • 1,123
  • 7
  • 8