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();
标签:__,sheet,openpyxl,lenght,自动,列宽,out From: https://www.cnblogs.com/love-DanDan/p/18005245