Saturday, January 14, 2023

Autofit the columns in excel using openpyxl,openpyxl part 5

 #autofit the columns


#planet_sheet = your current worksheet   
dims = {}
for row in planet_sheet.rows:
    for cell in row:
        if cell.value:
            #dims[cell.column] = max((dims.get(cell.column, 0), len(str(cell.value))))
            dims[cell.column_letter] = max((dims.get(cell.column_letter, 0), len(str(cell.value))))
for col, value in dims.items():
    planet_sheet.column_dimensions[col].width = value

 

Source:https://stackoverflow.com/questions/13197574/openpyxl-adjust-column-width-size

No comments:

Post a Comment