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

参考文章

相关推荐
LK_073 小时前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
wuyk5553 小时前
Python办公自动化-第02讲-Excel文件认知与四大库选型
开发语言·python·excel
用户54817845909504 小时前
Java 与 Python 在大模型与智能体领域的选型
java·python
yiangL_4 小时前
1、Python 输入输出实验|print 与 input 人机交互实践
开发语言·python·人机交互
高洁015 小时前
世界模型的因果内核:从预测表象到理解机制
人工智能·python·深度学习·transformer·迁移学习
数字融合5 小时前
透明化视频动态三维重建空间数据零核心技术
人工智能·python·virtualenv
AI创界者6 小时前
Python 进阶实战(五十四章):大模型推理网关终极架构——分布式全局前缀 Trie 缓存同步与多网关高可用协同调度
人工智能·python·aigc
萧子琦6 小时前
零第三方依赖能做到什么程度?开源两个纯标准库安全小工具:StarShield Forensics 与澄镜 ClearLens
python
用户91294046848426 小时前
Codex 从零到能交付(19):让 Codex 做代码审查:发现问题后怎样验证
python