python openpyxl 设置表格列宽的自动适应

导入:

from openpyxl import Workbook
from openpyxl.utils import get_column_letter

代码片段

	#获取每一列的内容的最大宽度
	i = 0
	# 每列
	 for col in self.sheet.columns:
	 	# 每行
	     for j in range(len(col)):
	         if j == 0:
	         	# 数组增加一个元素
	             col_width.append(len(str(col[j].value)))
	         else:
	         	# 获得每列中的内容的最大宽度
	            if col_width[i] < len(str(col[j].value)):
	                 col_width[i] = len(str(col[j].value))
	     i = i + 1
	      
 	#设置列宽
	for i in range(len(col_width)):
	    # 根据列的数字返回字母
	    col_letter = get_column_letter(i+1)
	    # 当宽度大于100,宽度设置为100
	    if col_width[i] > 100:
	        self.sheet.column_dimensions[col_letter].width = 100
	    # 只有当宽度大于10,才设置列宽
	    elif col_width[i] > 10:
	        self.sheet.column_dimensions[col_letter].width = col_width[i] + 2

你可能感兴趣的:(tech)