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()

参考文章

相关推荐
我材不敲代码1 小时前
Python实现打包贪吃蛇游戏
开发语言·python·游戏
0思必得04 小时前
[Web自动化] Selenium处理动态网页
前端·爬虫·python·selenium·自动化
韩立学长4 小时前
【开题答辩实录分享】以《基于Python的大学超市仓储信息管理系统的设计与实现》为例进行选题答辩实录分享
开发语言·python
qq_192779874 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
u0109272714 小时前
使用Plotly创建交互式图表
jvm·数据库·python
爱学习的阿磊4 小时前
Python GUI开发:Tkinter入门教程
jvm·数据库·python
Imm7775 小时前
中国知名的车膜品牌推荐几家
人工智能·python
tudficdew5 小时前
实战:用Python分析某电商销售数据
jvm·数据库·python
sjjhd6525 小时前
Python日志记录(Logging)最佳实践
jvm·数据库·python
2301_821369616 小时前
用Python生成艺术:分形与算法绘图
jvm·数据库·python