Python自适应调整Excel的列宽度

使用python调整列宽度的逻辑需要自己写,这里是参考参考文章中的内容,使用openpyxl打开文件后,将列宽度根据列的内容进行指定,使用max(列的内容宽度 + 2) * 1.2来指定列宽

示例程序

假设有一个测试.xlsx的文件,使用如下程序自适应的调整列宽度

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

参考文章

相关推荐

  1. Python适应调整Excel宽度

    2023-12-21 05:44:02       41 阅读
  2. 使用openpyxl调整Excel宽度

    2023-12-21 05:44:02       43 阅读
  3. el-dialog宽度适应

    2023-12-21 05:44:02       16 阅读
  4. uniapp app 实现适应宽度 input

    2023-12-21 05:44:02       38 阅读
  5. Unity InputField宽度适应内容

    2023-12-21 05:44:02       23 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-21 05:44:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-21 05:44:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-21 05:44:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-21 05:44:02       20 阅读

热门阅读

  1. Python控制Excel自动刷新页面

    2023-12-21 05:44:02       31 阅读
  2. 怎么防护服务器不被入侵

    2023-12-21 05:44:02       32 阅读
  3. MVC框架和Spring MVC的基本流程

    2023-12-21 05:44:02       35 阅读
  4. 华为云Stack 8.X 流量模型分析(一)

    2023-12-21 05:44:02       31 阅读
  5. 解决 MATLAB 启动速度慢的问题

    2023-12-21 05:44:02       60 阅读
  6. 第二十一章 : Spring Boot 集成RabbitMQ(五)

    2023-12-21 05:44:02       29 阅读
  7. Pytorch读写张量文件

    2023-12-21 05:44:02       46 阅读
  8. 基于redis的分布式锁实现方案

    2023-12-21 05:44:02       35 阅读
  9. python3 自定义比较器/比较函数

    2023-12-21 05:44:02       43 阅读