狂自私

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

openpyxl 列宽自动调整

openpyxl没有方便快捷的自动调整列宽的函数,只能自己写一个来实现。

复制代码
from openpyxl.styles import Alignment
from openpyxl import Workbook

#计算单双字节
def realLenght(s:str):
    p = re.compile(r'[^\x00-\xff]+')    #t提取双字节字符
    doubleBytenum = len(''.join(p.findall(s)))
    singleBytenum = len(s)-doubleBytenum
    return doubleBytenum*2+singleBytenum;
#调整列宽
def autoFit(active_sheet:any)->None:
    for col in active_sheet.columns:
        max_lenght = 0
        column = col[1].column_letter   #避免合并单元格的问题
        for cell in col:
            try:
                l=realLenght(str(cell.value))
                if(l>max_lenght):
                    max_lenght = l
            except:
                pass
        auto_width = (max_lenght+2)*1.1
        active_sheet.column_dimensions[column].width=auto_width;
if __name__ == '__main__':
  #调整列宽
  autoFit(out_sheet)
  out_wk = Workbook()
  out_sheet=out_wk.active
  out_wk.save();
复制代码

 

posted on   狂自私  阅读(642)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示