Python自适应调整Excel的列宽度

使用python调整列宽度的逻辑需要自己写,这里是参考参考文章中的内容,使用openpyxl打开文件后,将列宽度根据列的内容进行指定,使用max(列的内容宽度 + 2) * 1.2来指定列宽

示例程序

假设有一个测试.xlsx的文件,使用如下程序自适应的调整列宽度

py 复制代码
import openpyxl


def auto_resize_column(excel_path):
    """自适应列宽度"""
    wb = openpyxl.load_workbook(excel_path)
    worksheet = wb.active
    for col in worksheet.columns:
        max_length = 0
        column = col[0].column_letter  # Get the column name
        for cell in col:
            try:  # Necessary to avoid error on empty cells
                if len(str(cell.value)) > max_length:
                    max_length = len(str(cell.value))
            except:
                pass
        adjusted_width = (max_length + 2) * 1.2
        worksheet.column_dimensions[column].width = adjusted_width
    wb.save(excel_path)


def main():
    excel = auto_resize_column("测试.xlsx")


if __name__ == '__main__':
    main()

参考文章

相关推荐
databook5 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室5 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三6 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271110 小时前
Python之语言特点
python
刘立军10 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机14 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机15 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i16 小时前
django中的FBV 和 CBV
python·django
c8i16 小时前
python中的闭包和装饰器
python
葡萄城技术团队17 小时前
从100秒到10秒的性能优化,你真的掌握 Excel 的使用技巧了吗?
excel