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

参考文章

相关推荐
思则变12 分钟前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
漫谈网络41 分钟前
WebSocket 在前后端的完整使用流程
javascript·python·websocket
try2find2 小时前
安装llama-cpp-python踩坑记
开发语言·python·llama
博观而约取3 小时前
Django ORM 1. 创建模型(Model)
数据库·python·django
Prodigy_kyw3 小时前
VBA初学3----实战(VBA实现Excel转csv)
excel·vba·csv
精灵vector5 小时前
构建专家级SQL Agent交互
python·aigc·ai编程
Zonda要好好学习5 小时前
Python入门Day2
开发语言·python
Vertira5 小时前
pdf 合并 python实现(已解决)
前端·python·pdf
太凉5 小时前
Python之 sorted() 函数的基本语法
python
项目題供诗5 小时前
黑马python(二十四)
开发语言·python