Python—openpyxl快速设置Excel的单元格格式

Python处理Excel的问题方面,设置单元格格式是无法回避的,这里我主要用openpyxl处理。网上这种资料很多,我这里写了一个函数,汇总了一下。

from openpyxl import load_workbook
from openpyxl.utils import get_column_letter 
from openpyxl.styles import Font,Border,Side,PatternFill,Alignment
def set_cells(cells,type,color=None):
  aligncenter=Alignment(horizontal='center',vertical='center')  #居中
  sidestyle=Side(border_style='thin')
  border=Border(left=sidestyle,right=sidestyle,top=sidestyple,bottom=sidestyle)
  for i in cells:
    for j in i:
      if(type=='percent'):
        j.number_format='0.00%'
      elif(type=='bold'):
        j.style='Pandas'
      elif(type=='center'):
        j.alignment=aligncenter
      elif(type=='border'):
        j.border=border
      elif(type=='color'):
      	j.fill = PatternFill("solid", fgColor=color)  #solid为样式
#统一列的宽度
def set_width(ws,width):
  for i in range(1,ws.max_column+1):
    letter=get_column_letter(i)
    ws.column_dimensions[letter].width=width
        
wb=load_workbook(filename)
ws=wb['Sheet1']
rownum=str(ws.max_row)			  #总行数
letter=get_column_letter(ws.max_column) #最后一列的字母
cells=ws['A1:A100']               #单元格范围
cells=ws['A1:'+letter+rownum]	  #全部单元格范围
set_cells(cells,'percent')        #单元格为百分比
set_cells(cells,'bold')           #单元格字体加粗
set_cells(cells,'center')         #单元格居中
set_cells(cells,'border')         #单元格加边框
set_cells(cells,'color','FF0000') #单元格涂色
set_width(ws,16)				  #统一所有的列宽为16
wb.save()

如何确定单元格范围呢,比如要取最后一列,那就是

letter=get_column_letter(ws.max_column)
rownum=str(ws.max_row)

所以单元格范围就是

'A1:A'+rownum						#取第一列
letter+'1':letter+rownum			#取最后一列
'A1:'+letter+'1'					#取第一行
'A'+rownum+':'+letter+rownum		#取最后一行
’A1:'+letter+rownum					#全部行列

注意PatternFill 可以选择多个样式 只是solid最常用
在这里插入图片描述

  • 10
    点赞
  • 76
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值