openpyxl批量删除表格中的空白行,并处理数据样式

demo:

from excel封装关键字 import *
from openpyxl.styles import Font  # 导入字体模块
from openpyxl.styles import PatternFill  # 导入填充模块
from openpyxl.styles import Alignment

Color1 = 'ffeb9c' # 橙色
Color2 = 'c0c0c0'  #浅灰
Color3 = '000000' #黑色
fill_yellow = PatternFill('solid', fgColor=Color1)  # 设置填充颜色为 橙色
fill_grey = PatternFill('solid', fgColor=Color2)  # 设置填充颜色为 橙色
font = Font(u'等线', size=15, bold=True, italic=False, strike=False,color=Color3)  # 设置字体样式 bold=加粗 italic=斜体 strike=杠掉
alignment =Alignment(horizontal='center',vertical='center')    #水平和垂直的居中

excel = ParseExcel()
workbook1 = excel.loadWorkBook(excelPathAndName=r'C:\Users\frank\Desktop\for_test.xlsx')
sheet = excel.getSheetByIndex(sheetIndex = 0)

#获得删除之前的总行数
maxrow_before = sheet.max_row

#获得第一列每行的value,用于判断是否为none(是否需要删除)
list = excel.getColumn(sheet=sheet,colNo=1)
row_value_list = [i.value for i in list]


#批量删除表格中的空白行  由于删除的一行,下面的行数会顶上来,所以需要额外定义一个delete_index
delete_index = 1
for i in range(maxrow_before):
    if row_value_list[i] != None:
        delete_index += 1
    else:
        sheet.delete_rows(idx=delete_index)
        print('已删除第%d行'%delete_index)

#获得删除之后的总行数和总列数,用于更改数据样式
maxrow_after = sheet.max_row
maxcol = sheet.max_column

for i in range(maxrow_after):
    for j in range(maxcol):
        if i%2 == 0:
            sheet.cell(row=i+1 , column=j+1).fill = fill_grey
            sheet.cell(row=i + 1, column=j + 1).alignment = alignment
        else:
            sheet.cell(row=i + 1, column=j + 1).alignment = alignment
        sheet.cell(row=1 , column=j+1).fill = fill_yellow
        sheet.cell(row=1 , column=j+1).font = font
        sheet.cell(row=1 , column=j+1).alignment = alignment

workbook1.save(filename=r'C:\Users\frank\Desktop\for_test.xlsx')

你可能感兴趣的:(python,python)