如何用Python操作Excel自动化办公?一个案例教会你openpyxl——样式和条件格式

《如何用Python操作Excel自动化办公?一个案例教会你openpyxl——样式和条件格式》

虽然现在各种各样强大的工具很多,但是人人都离不开Excel,原因就在于简单易用、快捷DIY。它不仅是CRUD(增删改查)的工具,也是可视化设计便利的工具。日常工作中,除了基本的数据处理,还需要对Excel表格、单元格、图表进行格式整理、样式美化,便于直观明确的传达信息。本篇接着上两篇讲解如何让通过openpyxl进行单元格合并、边框、字体、颜色、行高列宽、对齐等功能。

话不多说,来上代码演示。

1. 工作表属性格式

首先导入数据:

from openpyxl import Workbook, load_workbook
from openpyxl.utils import get_column_letter, column_index_from_string
wbo = load_workbook(r"D:\7_Python\pyproject\testOrders5.xlsx")
ws1 = wbo['replacelist']

设置工作表标签颜色:

wsprops = wso.sheet_properties
wsprops.tabColor = "1072BA"  #蓝色渐变色
ws1props = ws1.sheet_properties
ws1props.tabColor = "EF8D45" #橙色满色

《如何用Python操作Excel自动化办公?一个案例教会你openpyxl——样式和条件格式》

《如何用Python操作Excel自动化办公?一个案例教会你openpyxl——样式和条件格式》

关于颜色代码怎么找,有方便的颜色代码查询网站,这里有链接:https://m.fontke.com/tool/rgb/

2. 设置单元格内容字体

对单元格的设置需要导入styles函数包,里面包括了字体、颜色、合并等

from openpyxl.styles import Font,colors,Alignment,Border

2.1 调整字体

一般对单元格格式的设置,都是先调用一个格式对象,把你需要的属性都设置好,然后再赋值给对应单元格:

font_itatic_bold_20 = Font(name='等线', size=24, italic=True, color="EF8D45", bold=True)
ws1['A1'].font = font_itatic_bold_20

上面代码表明先创建字体对象,字体名字为“等线”,大小为20,italic(是否需要斜体),颜色代码、是否加粗。设置好后就把对象赋值给A1单元格的字体属性。效果如下:

《如何用Python操作Excel自动化办公?一个案例教会你openpyxl——样式和条件格式》

这样我就把字体给设置了,可以任意调整参数来达到想要的效果。但是这里我们看到字体调大了就会被遮挡。所以需要调整一下第一列列距,同时也想调整一下第一行行距。

2.2 调整行列间距

运行以下代码:

ws1.row_dimensions[1].height = 30  # 第1行行高
ws1.column_dimensions['A'].width = 20  # A列列宽

《如何用Python操作Excel自动化办公?一个案例教会你openpyxl——样式和条件格式》

2.3 批量调整字体、行列间距

for i in range(1,3):
    for j in range(1, 5):
        ws1['{}{}'.format(get_column_letter(i),j)].font = font_itatic_bold_20
for m in range(1,5):
    ws1.row_dimensions[m].height = 30
for n in range(1,3):
    ws1.column_dimensions[get_column_letter(n)].width = 20

《如何用Python操作Excel自动化办公?一个案例教会你openpyxl——样式和条件格式》

实际上要实现批量很简单,只要加入循环就可以,按照要求的格式循环写入就能实现快速调整格式。后面的格式调整都可以采用这种方式。有的朋友可能想实现不同单元格区域设置不同格式,这当然没有捷径了,需要分别循环调整。

2.4 合并和拆分单元格

有时候我需要对单元格进行合并或者拆分怎么办呢?比如这里我需要把工作簿的sheet1表里的TerritoryKey列相同的数据进行合并。合并操作处理的方式是以合并区域的左上角的那个单元格为基准,覆盖其他单元格使之称为一个大的单元格。

wso.merge_cells('E7:E10') # 合并一个矩形区域中的单元格

《如何用Python操作Excel自动化办公?一个案例教会你openpyxl——样式和条件格式》

合并之后就只剩下合并区域左上角第一个单元格的值了。反之想要拆分单元格也很简单。

wso.unmerge_cells('E7:E10')

《如何用Python操作Excel自动化办公?一个案例教会你openpyxl——样式和条件格式》

拆分之后只有左上角第一个单元格有值,其他都没有值。这里我想尝试给下面的单元格写入相同的值,该怎么办呢?正常的思路是循环写入第一个单元格的值:

《如何用Python操作Excel自动化办公?一个案例教会你openpyxl——样式和条件格式》

然而却报错了(上图所示)。尝试改用delete直接删除,然而这种方法只能删除内容,格式还是被锁定的。原因是合并后,代码默认其他单元格应该是空值且不能被赋新值。那怎么办呢?把合并过的区域给清除合并就可以了。

wso._clean_merge_range('E7:E10') #清除合并格式

2.5 对齐方式

我想把单元格内容位置进行调整,就需要用到对齐方式:

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。

《如何用Python操作Excel自动化办公?一个案例教会你openpyxl——样式和条件格式》

2.6 单元格填充

如果想要对单元格进行填充怎么办?

fill = PatternFill(patternType="solid", start_color="33CCFF")
ws1['B1'].fill = fill

《如何用Python操作Excel自动化办公?一个案例教会你openpyxl——样式和条件格式》

fill_type类型有’none’、‘solid’、‘darkDown’、‘darkGray’、‘darkGrid’、‘darkHorizontal’、‘darkTrellis’、‘darkUp’、‘darkVertical’、‘gray0625’、‘gray125’、‘lightDown’、‘lightGray’、‘lightGrid’、‘lightHorizontal’、‘lightTrellis’、‘lightUp’、‘lightVertical’、‘mediumGray’。官方文档中写明,fill_type若没有特别指定类型,则后续的参数都无效,所以上述代码就会出问题,start_color代表前景色,end_color是背景色,之所以设置两个参数是为了方便样式颜色的填充和渐变色的显示,如果想要纯色填充的话可以用’solid’,然后令前景色为你需要的颜色即可。

2.7 添加边框

为了让数据区域区分明显,有时候需要添加边框,这是Excel常见功能。这里调用的方式还是很简单:

thin = Side(border_style="thin", color="EF8D45")  # 边框样式和颜色
border = Border(left=thin, right=thin, top=thin, bottom=thin)  # 边框的位置
ws1['B6'].border = border  # B6单元格设置边框
for row in ws1['A1:B4']:
    for cell in row:
        cell.border = border  # A1:B4区域单元格设置边框

《如何用Python操作Excel自动化办公?一个案例教会你openpyxl——样式和条件格式》

3. 条件格式

以上是我们单独为某个单元格或区域设置格式,但是还是比较麻烦,如果我想设置条件格式规则,让符合条件的自动设置相应的格式不是更好吗?

from openpyxl import formatting, styles
from openpyxl.styles import Color, PatternFill, Font, Border
from openpyxl.styles.differential import DifferentialStyle
from openpyxl.formatting import Rule
from openpyxl.formatting.rule import ColorScaleRule, CellIsRule, FormulaRule  

openpyxl中对条件格式有很多专门的库,需要导入才能使用。

3.1 大小比较条件格式

接下来需要对sheet1表中的销售金额进行判断,小于3000元的标注红色:

redFill = PatternFill(start_color='EE1111',end_color='EE1111',fill_type='solid')
wso.conditional_formatting.add('F2:F10',
             formatting.rule.CellIsRule(operator='lessThan', 
             formula=['3000'], stopIfTrue=True, fill=redFill)

《如何用Python操作Excel自动化办公?一个案例教会你openpyxl——样式和条件格式》

3.2 区间比较条件格式

如果想找出销售金额在3300到3400之间的金额呢?

wso.conditional_formatting.add('F2:F10',
             formatting.rule.CellIsRule(operator='between', 
             formula=['3300','3400'], stopIfTrue=True, fill=redFill))

《如何用Python操作Excel自动化办公?一个案例教会你openpyxl——样式和条件格式》

3.3 百分比突出条件格式

如果想按照数量百分比排序分别赋值颜色:

wso.conditional_formatting.add('F1:F10',
                ColorScaleRule(start_type='percentile',              start_value=10,start_color='AA0000',
mid_type='percentile', mid_value=50, mid_color='EF8D45',
end_type='percentile', end_value=90, end_color='1072BA')

《如何用Python操作Excel自动化办公?一个案例教会你openpyxl——样式和条件格式》

3.4 搜索条件格式

如果我想在单元格区域内搜寻符合条件的单元格用颜色显示:

red_text = Font(color="9C0006")
red_fill = PatternFill(bgColor="FFC7CE")
dxf = DifferentialStyle(font=red_text, fill=red_fill)
rule = Rule(type="containsText", operator="containsText", text="highlight", dxf=dxf)
rule.formula = ['NOT(ISERROR(SEARCH("C28389",A1)))']
wso.conditional_formatting.add('A1:F10', rule)

以上代码表达的意思是:第一行是设置突出显示的字体和颜色,第二行是设置填充颜色,第三行代码是创建一个条件格式实例,第四行是创建一个条件格式规则,第五行是设置好规则的判断公式,第六行是对选中区域应用条件格式规则。这里我要找的是在A1:F1里找出含有“C28389”内容的单元格用”FFC7CE”填充单元格突出显示。

《如何用Python操作Excel自动化办公?一个案例教会你openpyxl——样式和条件格式》

3.5 条件格式加边框

用另一种方式建立条件格式规则找出销售金额为3399.99的单元格,用边框的方式突出。

 wso.conditional_formatting.add('F1:F10',
        formatting.rule.FormulaRule(formula=['F1=3399.99'], 
                font=Font(), border=Border(, fill=redFill))

《如何用Python操作Excel自动化办公?一个案例教会你openpyxl——样式和条件格式》

3.5 条件格式数据条

我不想用颜色填充了,而用数据条来表示怎么做呢?

from openpyxl.formatting.rule import DataBar, FormatObject
first = FormatObject(type='min')
second = FormatObject(type='max')
data_bar = DataBar(cfvo=[first, second], color="638EC6", showValue=None, minLength=None, maxLength=None)
rule = Rule(type='dataBar', dataBar=data_bar)
wso.conditional_formatting.add('F1:F10',rule)

《如何用Python操作Excel自动化办公?一个案例教会你openpyxl——样式和条件格式》

4. 代码封装

样式和条件格式函数讲解了这么多,看到这里的朋友可能会觉得好麻烦啊,我每用一个就要写这么多代码吗?不是的,编程语言方便就方便在于只要你第一次代码写好跑通就可以封装成函数多次调用,下次稍微修改就可以使用了。下面对以上内送做一个简单的代封装:

from openpyxl import load_workbook
from openpyxl.utils import get_column_letter
from openpyxl.styles import Font,Border,Side,PatternFill,Alignment
def set_cells(cells,type,color=None):
    font_itatic_bold_20 = Font(name='等线', size=24, italic=True, color="EF8D45", bold=True)
    align = Alignment(horizontal='left',vertical='center',wrap_text=True)  #居中
    fill = PatternFill(patternType="solid", start_color="33CCFF")
    thin = Side(border_style="thin", color="EF8D45")  # 边框样式和颜色
    border = Border(left=thin, right=thin, top=thin, bottom=thin)  # 边框的位置
    for i in cells:
      for j in i:
        if(type=='percent'):
            j.number_format='0.00%'     #设置数字格式
        elif(type=='font'):
            j.font=font_itatic_bold_20  #设置字体
        elif(type=='center'):
            j.alignment=align           #设置对齐方式
        elif(type=='border'):
            j.border=border             #设置边框
        elif(type=='fill'):
            j.fill = fill               #设置填充样式

def set_width(ws,width):                #统一列的宽度
   for i in range(1,ws.max_column+1):
       letter=get_column_letter(i)
       ws.column_dimensions[letter].width=width

def conditional_format(cells,type,formula=None):
    myFont = Font()
    myBorder = Border()
    redFill = PatternFill(start_color='EE1111', end_color='EE1111', fill_type='solid')
    if(type=='lessThan'):                   
        wso.conditional_formatting.add('{}'.format(cells),formatting.rule.CellIsRule(operator='lessThan', formula=['{} < {}'.format(cells,value)],stopIfTrue=True, fill=redFill))  #设置大小比较格式
    elif(type=='between'):
        wso.conditional_formatting.add(cells, formatting.rule.CellIsRule(operator='between', formula=formula,stopIfTrue=True, fill=redFill))   #设置区间比较格式
    elif(type=='border'):
        wso.conditional_formatting.add(cells,formatting.rule.FormulaRule(formula=formula, font=myFont, border=myBorder,fill=redFill))         #设置边框
        
if __name__ == "__main__": 
           set_cells()
           set_width()
           conditional_format()

内容看似很多,但其实当你用的熟练,会跟用鼠标操作Excel表格那样容易,把常用的格式设置封装好,就可以免去重复性操作的麻烦。有朋友会说pandas也可以设置样式和格式,但是能细化到单元格还是openpyxl比较便利一些。欢迎大家收藏本篇,如果有需要可以随时查看。如果大家需要数据集或者有什么不明白的,可以关注同名”二八Data”,私戳我。下一篇文章将讲解怎么调整工作表的表格样式和图表。

最后欢迎大家关注我,我是拾陆,关注同名”二八Data“,更多干货持续为你奉献。《如何用Python操作Excel自动化办公?一个案例教会你openpyxl——样式和条件格式》

    原文作者:DataMiningSharer
    原文地址: https://blog.csdn.net/lqw844597536/article/details/121911843
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞