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

参考文章

相关推荐
汤姆yu15 分钟前
基于python的化妆品销售分析系统
开发语言·python·化妆品销售分析
上去我就QWER1 小时前
Python下常用开源库
python·1024程序员节
程序员杰哥2 小时前
Pytest之收集用例规则与运行指定用例
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
Jyywww1212 小时前
Python基于实战练习的知识点回顾
开发语言·python
朝朝辞暮i3 小时前
从0开始学python(day2)
python
程序员黄同学3 小时前
Python中的列表推导式、字典推导式和集合推导式的性能和应用场景?
开发语言·python
AI小云3 小时前
【Python高级编程】类和实例化
开发语言·人工智能·python
道之极万物灭3 小时前
Python uv虚拟环境管理工具详解
开发语言·python·uv
高洁014 小时前
【无标题】大模型-模型压缩:量化、剪枝、蒸馏、二值化 (2
人工智能·python·深度学习·神经网络·知识图谱
一晌小贪欢4 小时前
Python爬虫第10课:分布式爬虫架构与Scrapy-Redis
分布式·爬虫·python·网络爬虫·python爬虫·python3