[爬虫]对excel表格设置样式
要求:
1、设置列宽
2、冻结窗格
3、设置表头背景色、对齐方式、加粗
4、条件格式
代码:
#单 位:常州旺龙
#作 者:OLDNI
#开发日期:2023/10/26
"""
设置excel表格样式
"""
import os
from openpyxl import load_workbook
from openpyxl.styles import Font, PatternFill, Alignment
wb=load_workbook('鸟云平台库存数据.xlsx')
sheet=wb.active
#设置列宽
column_number_and_dimensions={'A':30,'B':25,'C':25,'D':25,'E':25,'F':25,'G':25,}
for n,d in column_number_and_dimensions.items():
sheet.column_dimensions[n].width = d
#冻结窗格
sheet.freeze_panes='B2'
#设置表头样式
cells=sheet[1]
font=Font(bold=True)
patternfill=PatternFill(fill_type='solid',fgColor='FFFF00')
alignment=Alignment(horizontal='center')
for cell in cells:
cell.font=font
cell.fill=patternfill
cell.alignment=alignment
#D列内容凡是"禁用"就填充红色(解决条件格式问题)
patternfill=PatternFill(fill_type='solid',fgColor='FF0000')
cells=sheet['D']
for cell in cells:
if cell.value=='禁用':
cell.fill=patternfill
wb.save('鸟云平台库存数据_test.xlsx')
os.startfile('鸟云平台库存数据_test.xlsx')
效果: