python openpyxl 设置表格列宽的自动适应,Python-自动调整Excel文件列的宽度

本文介绍了一种Python脚本,使用openpyxl库自动调整Excel文件中所有列的宽度,以适应其内容。通过遍历工作表的每一列,找到最长的单元格值,并根据该长度设置列宽。调整的宽度考虑了字符数和字体大小,可以灵活调整以适应不同字体。这是一个无需手动指定每列宽度的方法。
摘要由CSDN通过智能技术生成

Newbie - I have a Python script that adjusts the width of different columns of an excel file, according to the values specified:

import openpyxl

from string import ascii_uppercase

newFile = "D:\Excel Files\abc.xlsx"

wb = openpyxl.load_workbook(filename = newFile)

worksheet = wb.active

for column in ascii_uppercase:

if (column=='A'):

worksheet.column_dimensions[column].width = 30

elif (column=='B'):

worksheet.column_dimensions[column].width = 40

elif (column=='G'):

worksheet.column_dimensions[column].width = 45

else:

worksheet.column_dimensions[column].width = 15

wb.save(newFile)

Is there any way through which we can adjust the width of every column to its most optimum value, wit

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值