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

参考文章

相关推荐
U盘失踪了21 小时前
python 调用deepseek api生成测试用例
python·测试用例
火云洞红孩儿1 天前
告别界面孤岛:PyMe如何用一站式流程重塑Python GUI开发?
开发语言·python
攻城狮7号1 天前
不懂代码也能造?TRAE+GLM-4.6 手把手教你搭心理咨询智能客服小程序
python·小程序·uni-app·vue·trae·glm我的编程搭子·glm-4.6
叫我辉哥e11 天前
新手进阶Python:办公看板集成ERP跨系统同步+自动备份+AI异常复盘
开发语言·人工智能·python
布局呆星1 天前
闭包与装饰器
开发语言·python
全栈测试笔记1 天前
异步函数与异步生成器
linux·服务器·前端·数据库·python
木头左1 天前
基于Backtrader框架的指数期权备兑策略实现与分析
python
素心如月桠1 天前
cmd 输入 python --version 输出为空(windows11系统安装python后执行python --version没反应)
python
飞Link1 天前
深度解析 HyperLPR:高性能中文车牌识别框架从入门到实战
python
QQ588501981 天前
Python_uniapp-心理健康测评服务微信小程序的设计与实现
python·微信小程序·uni-app