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

参考文章

相关推荐
2501_944452238 小时前
字数统计 Cordova 与 OpenHarmony 混合开发实战
python
骚戴8 小时前
2025 Python AI 实战:零基础调用 LLM API 开发指南
人工智能·python·大模型·llm·api·ai gateway
kobe_OKOK_8 小时前
tdeinge REST API 客户端
python·缓存·django
io_T_T8 小时前
Python os库 os.walk使用(详细教程、带实践)
python
TonyLee0179 小时前
使用argparse模块以及shell脚本
python
Blossom.1189 小时前
Prompt工程与思维链优化实战:从零构建动态Few-Shot与CoT推理引擎
人工智能·分布式·python·智能手机·django·prompt·边缘计算
love530love11 小时前
Windows 11 下 Z-Image-Turbo 完整部署与 Flash Attention 2.8.3 本地编译复盘
人工智能·windows·python·aigc·flash-attn·z-image·cuda加速
MediaTea12 小时前
Python:模块 __dict__ 详解
开发语言·前端·数据库·python
jarreyer12 小时前
python,numpy,pandas和matplotlib版本对应关系
python·numpy·pandas
代码or搬砖12 小时前
HashMap源码
开发语言·python·哈希算法