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

参考文章

相关推荐
都叫我大帅哥10 分钟前
决策树:从零开始的机器学习“算命大师”修炼手册
python·机器学习
这里有鱼汤10 分钟前
首个支持A股的AI多智能体金融系统,来了
前端·python
云霄IT28 分钟前
python使用ffmpeg录制rtmp/m3u8推流视频并按ctrl+c实现优雅退出
python·ffmpeg·音视频
都叫我大帅哥34 分钟前
我给大模型装上“记忆黄金券”:LangChain的ConversationSummaryBufferMemory全解析
python·langchain·ai编程
桃子叔叔36 分钟前
28天0基础前端工程师完成Flask接口编写
前端·python·flask
德育处主任1 小时前
『OpenCV-Python』配合 Matplotlib 显示图像
后端·python·opencv
仰望星空的凡人8 小时前
【JS逆向基础】数据库之MongoDB
javascript·数据库·python·mongodb
F_D_Z8 小时前
【PyTorch】图像多分类项目部署
人工智能·pytorch·python·深度学习·分类
pingzhuyan10 小时前
python入门篇12-虚拟环境conda的安装与使用
python·ai·llm·ocr·conda
香蕉可乐荷包蛋10 小时前
排序算法 (Sorting Algorithms)-Python示例
python·算法·排序算法