python openpyxl cell width 1

python openpyxl cell width

from openpyxl.utils import get_column_letter

column_widths = []
for row in Workbook:
    for i, cell in enumerate(row):
        if len(column_widths) > i:
            if len(cell) > column_widths[i]:
                column_widths[i] = len(cell)
        else:
            column_widths += [len(cell)]

for i, column_width in enumerate(column_widths):
    worksheet.column_dimensions[get_column_letter(i+1)].width = column_width

Here is what the above code is Doing:
1. Create an empty list called column_widths
2. Loop through each row in the worksheet
3. Loop through each cell in the row
4. If the column_widths list has an index for the current cell, compare the length of the cell contents to the value already in the list. If the cell contents are longer, replace the value in the list.
5. If the column_widths list doesn’t have an index for the current cell, add the length of the cell contents to the list.
6. Loop through each column width in the list and set the width of the column to the value in the list.

Similar Posts