需求描述:
共有多个业务部门,报表都放在 “各部门利润表汇总” 的文件夹下,需要把这些报表的格式统一。
报表原样式:
报表目的样式:
格式变化分析:
1.列宽:原表格列宽相同,而目的表格列宽个有不同;
2.颜色:目的表格包含三个颜色,分别对应第一行、最后一行还有中间几行的单元格;
3.边框:目的表格增加了边框下滑线;
4.对齐方式:新表格对齐方式采用居中。
#!/user/bin/env python
#--coding: utf-8--
#@Time : 2021/2/8 14:01
#@Author : GodSpeed
#@File : py_excel_modify_style.py
#@Software : PyCharm
import os
from openpyxl import load_workbook
from openpyxl.styles import PatternFill, Alignment, Side, Border
def excel_dict_sytle():
dict_sytle = {}
# 定义表头颜色样式为橙色
dict_sytle[‘header_fill’] = PatternFill(‘solid’, fgColor=‘FF7F24’)
# 定义表中颜色样式为淡黄色
dict_sytle[‘content_fill’] = PatternFill(‘solid’, fgColor=‘FFFFE0’)
# 定义表尾颜色样式为淡桔红色
dict_sytle[‘bottom_fill’] = PatternFill(‘solid’, fgColor=‘EE9572’)
# 定义对齐样式横向居中、纵向居中
dict_sytle['align'] = Alignment(horizontal='center', vertical='center')
# 定义边样式为细条
side = Side('thin')
# 定义表头边框样式,有底边和右边
dict_sytle['header_border'] = Border(bottom=side, right=side)
# 定义表中、表尾边框样式,有左边
dict_sytle['content_border'] = Border(left=side)
return dict_sytle
def excel_style_modify_fun(excel_files_path):
dict_sytle = excel_dict_sytle()
try:
files = os.listdir(excel_files_path)
except Exception as ex:
print('excel_files_path err ',excel_files_path)
return
for file in files:
#print(file)
file_path = excel_files_path + file
print(file_path)
# 打开工作簿
wb = load_workbook(file_path)
# 打开工作表
ws = wb.active
# 调整列宽
ws.column_dimensions['A'].width = 10
ws.column_dimensions['B'].width = 25
ws.column_dimensions['C'].width = 50
ws.column_dimensions['D'].width = 10
ws.column_dimensions['E'].width = 20
ws.column_dimensions['F'].width = 15
# 循环第一行单元格,调整表头样式
for cell in ws[1]:
# 设置单元格填充颜色
cell.fill = dict_sytle['header_fill']
# 设置单元格对齐方式
cell.alignment = dict_sytle['align']
# 设置单元格边框
cell.border = dict_sytle['header_border']
# 从第二行开始,循环到倒数第二行
for row in ws.iter_rows(min_row=2, max_row=(ws.max_row - 1)):
# 循环取出单元格,调整表中样式
for cell in row:
cell.fill = dict_sytle['content_fill']
cell.alignment = dict_sytle['align']
cell.border = dict_sytle['content_border']
# 循环最后一行单元格,调整表尾样式
for cell in ws[ws.max_row]:
cell.fill = dict_sytle['bottom_fill']
cell.alignment = dict_sytle['align']
cell.border = dict_sytle['content_border']
# 保存
wb.save(file_path)
if name == ‘main’:
excel_files_path = ‘./各部门利润表汇总/’
excel_style_modify_fun(excel_files_path)
小结
1.调整列宽用到的语句是Sheet.column_dimensions[‘列位置’].width = 列宽
如: ws.column_dimensions[‘A’].width = 10
2.单元格样式包括填充颜色fill、边框border、对齐方式alignment,分别是PatternFill、Border、 Side(‘thin’)对象
fill = PatternFill(‘solid’, fgColor=‘FF7F24’)
alignment = Alignment(horizontal=‘center’, vertical=‘center’)
border = Border(bottom= Side(‘thin’), right= Side(‘thin’))