五、Openpyxl工作表對(duì)象的屬性和方法-3(條件格式)

Conditional Formatting 條件格式

ColorScale 色階

語(yǔ)法

ColorScaleRule(start_type=None, start_value=None, start_color=None, mid_type=None, mid_value=None, mid_color=None, end_type=None, end_value=None, end_color=None)

type的值有

  • num 數(shù)字
  • percent 百分比
  • max 最大
  • min 最小
  • formula 公式
  • percentile 百分點(diǎn)數(shù)值

色階有雙色色階以及三色色階,如果是雙色的話就沒有mid_type等參數(shù)

雙色色階
三色色階

實(shí)例

import openpyxl
from openpyxl.formatting.rule import ColorScaleRule

wb = openpyxl.load_workbook('/Users/junliangchen/Desktop/data.xlsx')

ws = wb.active

rule = ColorScaleRule(start_type='percent',start_value=30,start_color='FC556C',  # 紅
                       mid_type='percent',mid_value=60,mid_color='E5E500',  # 黃
                       end_type='percent',end_value=90,end_color='1BA135') # 綠

ws.conditional_formatting.add('A2:A9',rule) # 將設(shè)置好的規(guī)則添加到工作表的條件格式中

wb.save('/Users/junliangchen/Desktop/data.xlsx')

IconSet 圖標(biāo)集

語(yǔ)法

IconSetRule(icon_style=None, type=None, values=None, showValue=None, percent=None, reverse=None)

參數(shù)詳解
  • icon_style:圖標(biāo)的樣式
'3Arrows', '3ArrowsGray', '3Flags', '3TrafficLights1',
'3TrafficLights2', '3Signs', '3Symbols', '3Symbols2',
'4Arrows', '4ArrowsGray', '4RedToBlack', '4Rating',
'4TrafficLights', '5Arrows', '5ArrowsGray', '5Rating', '5Quarters'
  • type同上
  • showValue:bool值,是否顯示值
  • reverse:bool值,
圖片說明

實(shí)例


import openpyxl
from openpyxl.formatting.rule import IconSetRule
from openpyxl.formatting.formatting import ConditionalFormattingList

wb = openpyxl.load_workbook('/Users/junliangchen/Desktop/data.xlsx')

ws = wb.active

ws.conditional_formatting = ConditionalFormattingList() # 清除工作表中的條件格式


rule = IconSetRule(icon_style='3Arrows',values=[0,60,80],type='percent',showValue=True)

ws.conditional_formatting.add('A2:A9',rule)  # 將設(shè)置好的規(guī)則添加到工作表的條件格式中

wb.save('/Users/junliangchen/Desktop/data.xlsx')

DataBar 數(shù)據(jù)條

語(yǔ)法

DataBarRule(start_type=None, start_value=None, end_type=None, end_value=None, color=None, showValue=None, minLength=None, maxLength=None)

這邊數(shù)據(jù)條可以設(shè)置比較少,沒有Excel軟件里的功能豐富,設(shè)置一下type,value,color就可以了,type 還是和上面的一樣。


FormulaRule

語(yǔ)法

當(dāng)滿足公式條件時(shí),設(shè)置樣式(字體,邊框,填充色)
FormulaRule(formula=None, stopIfTrue=None, font=None, border=None, fill=None)


import openpyxl
from openpyxl.formatting.rule import FormulaRule
from openpyxl.styles import PatternFill
from openpyxl.formatting.formatting import ConditionalFormattingList


wb = openpyxl.load_workbook(r'/Users/junliangchen/Desktop/data.xlsx')

ws = wb.active

ws.conditional_formatting = ConditionalFormattingList() # 把原本的條件格式列表清空

r = PatternFill(start_color='FA2B44',  # 紅色
               end_color='FA2B44',
                fill_type='solid')


#   下面公式的意思是,A列里名稱包含A,且C列的值大于40的單元格設(shè)置條件格式,當(dāng)滿足公式時(shí),設(shè)置紅色的填充色
rule1 = FormulaRule(formula=['=AND(IFERROR(FIND("A",A2),FALSE)=1,C2>40)'],fill=r)

ws.conditional_formatting.add('C2:C7',rule1)


wb.save(r'/Users/junliangchen/Desktop/data.xlsx')


CellIsRule

語(yǔ)法

CellIsRule(operator=None, formula=None, stopIfTrue=None, font=None, border=None, fill=None)

參數(shù)

  • operator

">": "greaterThan", 
">=": "greaterThanOrEqual", 
"<": "lessThan", 
"<=": "lessThanOrEqual",
"=": "equal", 
"==": "equal", 
"!=": "notEqual"

'between','notBetween'

單元格規(guī)則能設(shè)置就是這些

CellIsRule

實(shí)例

數(shù)字在5-15之間,都設(shè)置成紅色填充


import openpyxl
from openpyxl.formatting.rule import CellIsRule
from openpyxl.formatting.formatting import ConditionalFormattingList
from openpyxl.styles import PatternFill


wb = openpyxl.load_workbook('/Users/junliangchen/Desktop/data.xlsx')

ws = wb.active

r = PatternFill(start_color='FA2B44',  # 紅色
               end_color='FA2B44',
                fill_type='solid')

ws.conditional_formatting = ConditionalFormattingList() # 清除工作表中的條件格式

rule = CellIsRule(operator='between',formula=[5,15],fill=r)


ws.conditional_formatting.add('A1:A9',rule) # 將設(shè)置好的規(guī)則添加到工作表的條件格式中

wb.save('/Users/junliangchen/Desktop/data.xlsx')


Rule

除了上面這些規(guī)則可以設(shè)置,還有以下這些。

p1

p2

p3

p4

p5

語(yǔ)法

Rule(type, dxfId=int, priority=int, stopIfTrue=bool, aboveAverage=bool, percent=bool, bottom=bool, operator=, text=str, timePeriod=, rank=int, stdDev=int, equalAverage=bool, formula=(), colorScale=None, dataBar=None, iconSet=None, dxf=None)

關(guān)鍵參數(shù)

type

選擇規(guī)則的類型

'expression', 'cellIs', 'colorScale', 'dataBar',
'iconSet', 'top10', 'uniqueValues', 'duplicateValues', 'containsText',
'notContainsText', 'beginsWith', 'endsWith', 'containsBlanks',
'notContainsBlanks', 'containsErrors', 'notContainsErrors', 'timePeriod', 'aboveAverage'
operator
'lessThan', 'lessThanOrEqual', 'equal', 'notEqual', 'greaterThanOrEqual', 
'greaterThan', 'between', 'notBetween', 'containsText', 'notContains', 
'beginsWith', 'endsWith'
timePeriod時(shí)間點(diǎn)

當(dāng)你設(shè)置的規(guī)則是根據(jù)“發(fā)生日期”,就會(huì)用到以下參數(shù)。

'today', 'yesterday', 'tomorrow', 'last7Days',
 'thisMonth', 'lastMonth', 'nextMonth', 'thisWeek', 'lastWeek',
 'nextWeek'

好多參數(shù)對(duì)照上面圖片,或者打開Excel軟件看看,都能明白它的意思。就不細(xì)說了。

注意:這里面參數(shù)并沒有設(shè)置fill,border,font的,需要通過dxf設(shè)置樣式
需要導(dǎo)入下面模塊

from openpyxl.styles.differential import DifferentialStyle

實(shí)例

給單元格區(qū)域中,文本等于price的設(shè)置紅色填充


import openpyxl
from openpyxl.formatting.rule import Rule
from openpyxl.formatting.formatting import ConditionalFormattingList
from openpyxl.styles import PatternFill,Font
from openpyxl.styles.differential import DifferentialStyle


wb = openpyxl.load_workbook('/Users/junliangchen/Desktop/data.xlsx')

ws = wb.active

ws.conditional_formatting = ConditionalFormattingList() # 清除工作表中的條件格式

r = PatternFill(start_color='FA2B44',  # 紅色
               end_color='FA2B44',
                fill_type='solid')

my_sytle = DifferentialStyle(font=Font(name='宋體',size=12,bold=True),fill=r) # 自定義的樣式




rule = Rule(type='containsText',text='price',dxf=my_sytle,operator='containsText',formula=['NOT(ISERROR(SEARCH("price",A1)))'])


ws.conditional_formatting.add('A1:A9',rule) # 將設(shè)置好的規(guī)則添加到工作表的條件格式中

wb.save('/Users/junliangchen/Desktop/data.xlsx')


問題

我一開始是這樣子寫的,當(dāng)單元格text=price時(shí)設(shè)置紅色填充色,但是這樣子寫沒有效果,然后我看官方文檔是多了一個(gè)formula參數(shù)。

rule = Rule(type='containsText',text='price',dxf=my_sytle,operator='containsText')

官方的教程

這就很不合理了,明明說好用A方案來解決,你卻用了B方案,明明要求是設(shè)置當(dāng)?shù)扔谔囟ㄎ谋緯r(shí)設(shè)置樣式,你卻用滿足某個(gè)公式時(shí)設(shè)置樣式。那如果要滿足公式設(shè)置樣式的話,還不如像下面這樣寫。

rule = Rule(type='expression',formula=['NOT(ISERROR(SEARCH("price",A1)))'],dxf=my_sytle)

清除條件格式

上面列子有提到

from openpyxl.formatting.formatting import ConditionalFormattingList
worksheet.conditional_formatting = ConditionalFormattingList() # 清除工作表中的條件格式
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容