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

参考文章

相关推荐
李高钢19 分钟前
Python FastAPI 框架入门:从零搭建你的第一个高性能 API 服务
数据库·python·fastapi
ocean21031 小时前
2025-2026年Python面试高频知识点洞察
开发语言·python·面试·python八股文
Warson_L1 小时前
Python的OrderedDict
python
隐擎fox1 小时前
高性能网络爬虫架构设计:基于 Python 的长连接复用与分布式会话池调度实践
分布式·python·网络协议·tcp/ip·高并发·网络爬虫、
Warson_L1 小时前
Python的TypedDict
python·langchain·llm
晓窗科技2 小时前
口碑好的AI基座服务商
大数据·人工智能·python
小灰灰搞电子2 小时前
Python 信号量详解:并发控制实战
python·信号量
新时代牛马3 小时前
cyclictest 毛刺从哪来?从ftrace、latencytop、perf到IRQ/调度延迟定位
android·开发语言·python·kotlin
Dxy12393102163 小时前
Python如何结合AI解决数据分析问题
人工智能·python·数据分析
IvanCodes3 小时前
Python 基础语法(七):推导式与常见遍历写法
开发语言·python