openpyxl 学习笔记

openpyxl 学习笔记

from openpyxl import load_workbook, workbook
from openpyxl.styles import PatternFill, Side, Border, Alignment
import os

path = '../example/各部门利润表汇总_副本/'
files = os.listdir('../example/各部门利润表汇总_副本/')

# 填充样式
head_pattern = PatternFill(fill_type='darkVertical', fgColor='FF7F24')  
body_pattern = PatternFill(fill_type='darkVertical', fgColor='FFFFE0')
rear_pattern = PatternFill(fill_type='darkVertical', fgColor='EE9572')

# 居中设置
alig = Alignment(horizontal='center', vertical='top')
#边框格式
side = Side('thin')
border = Border(bottom=side)

# 打开工作表
for sample_file in files:
    file_path = path + sample_file
    #print(file_path) 文件路径
    wb = load_workbook(file_path)
    ws = wb.active
    bottom_row = ws.max_row		#最后行 行号
    
    for cell in ws[1]:		#第一行格式调整
        cell.fill = head_pattern
        cell.alignment = alig
        cell.border = border
        
    
    for cell in ws[bottom_row]:			#尾行格式调整
        cell.fill = rear_pattern
        cell.alignment = alig
        cell.border = border
        
    for row in ws.iter_rows(min_row=2, max_row=bottom_row-1):   #中间行格式调整
        for cell in row :
            cell.fill = body_pattern
            cell.alignment = alig
            cell.border = border
    wb.save(file_path)   		#保存当前工作簿




















openpyxl 学习笔记_第1张图片

你可能感兴趣的:(Python,学习笔记,excel)