Python - Automatically adjust width of an excel file's columns

后端 未结 6 1734
夕颜
夕颜 2021-02-01 22:15

Newbie - I have a Python script that adjusts the width of different columns of an excel file, according to the values specified:

import openpyxl
from string impo         


        
6条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-01 22:30

    Based on the comment above and add this post openpyxl - adjust column width size. I succeeded, but the answer should be:

    from openpyxl.utils import get_column_letter
    
    for col in ws.columns:
        max_length = 0
        column = get_column_letter(col[0].column)  # Get the column name
        # Since Openpyxl 2.6, the column name is  ".column_letter" as .column became the column number (1-based)
        for cell in col:
            try:  # Necessary to avoid error on empty cells
                if len(str(cell.value)) > max_length:
                    max_length = len(cell.value)
            except:
                pass
        adjusted_width = (max_length + 2) * 1.2
        ws.column_dimensions[column].width = adjusted_width
    

    i'm using openpyxl = "^3.0.5"

提交回复
热议问题