Python 单元格背景,字体,边框设置

单元格背景色设置

from openpyxl import load_workbook
from openpyxl.styles import PatternFill, colors

filename = r"E:\Coding\E_PythonWriting\Excel\openpyxl示例_4.xlsx"
wb = load_workbook(filename)
ws
= wb.worksheets[0] #定义背景颜色 color1 = PatternFill("solid", fgColor="BCEE68") color2 = PatternFill("solid", fgColor="FFFF00") color3 = PatternFill("solid", fgColor="FF0000") color4 = PatternFill("solid", fgColor="FFD700") ws["A1"].fill = color2 wb.save(excel_address)

 

Font:来设置文字的大小,颜色和下划线等

from openpyxl.styles import Font

font=Font(name='微软雅黑',size=11,bold=True,italic=True,strike=True,color='000000')

ws['A1'].font = font

#设置字体为“微软雅黑”,大小为11,bold为加粗,italic为斜体,strike为删除线,颜色为黑色

 

Border:单元格的边框

from openpyxl.styles import Border,Side
border
= Border(left=Side(border_style='thin',color='000000'), right=Side(border_style='thin',color='000000'), top=Side(border_style='thin',color='000000'), bottom=Side(border_style='thin',color='000000'))

ws[
"A1"].border = border

#注意这里需要导入Border和Side两个函数,如果没有定义边框的样式,那么后面的参数将没有作用,边框的样式有很多,官方给出的样式如下:

‘dashDot’,‘dashDotDot’,‘dashed’,‘dotted’,‘double’,‘hair’,‘medium’,‘mediumDashDot’,‘mediumDashDotDot’,‘mediumDashed’,‘slantDashDot’,‘thick’,‘thin’

 

Alignment:单元格的对齐方式等

from openpyxl.styles import Alignment

align = Alignment(horizontal='left',vertical='center',wrap_text=True)

ws['A1'].alignment = align

horizontal代表水平方向,可以左对齐left,还有居中center和右对齐right,分散对齐distributed,跨列居中centerContinuous,两端对齐justify,填充fill,常规general

vertical代表垂直方向,可以居中center,还可以靠上top,靠下bottom,两端对齐justify,分散对齐distributed

另外还有自动换行:wrap_text,这是个布尔类型的参数,这个参数还可以写作wrapText

合并单元格:

ws.merge_cells('A2:A10')  #合并A2到A10之间的单元格

 

设置行高与列宽

# 设置行高
ws.row_dimensions[1].height = 30
 
# 设置列宽
ws.column_dimensions['A'].width = 13

 

设置冻结单元格


ws.freeze_panes = 'B1' # 冻结第一列 ws.freeze_panes = 'A2' # 冻结第一行 ws.freeze_panes = 'B2' # 同时冻结第一行和第一列

 

  1.  
     
     
     
     
posted @ 2021-08-01 16:22  局域网外  阅读(1274)  评论(1编辑  收藏  举报