Python設(shè)置Excel條件格式的實(shí)戰(zhàn)教程
在 Excel 數(shù)據(jù)處理中,條件格式是一項(xiàng)強(qiáng)大的功能,它可以根據(jù)單元格值自動(dòng)應(yīng)用不同的格式樣式,幫助快速識(shí)別數(shù)據(jù)模式、趨勢(shì)和異常值。本文將介紹如何使用 Python 在 Excel 工作表中應(yīng)用條件格式,實(shí)現(xiàn)數(shù)據(jù)的可視化展示。
條件格式廣泛應(yīng)用于財(cái)務(wù)報(bào)表分析、銷售數(shù)據(jù)監(jiān)控、成績(jī)?cè)u(píng)估等場(chǎng)景。通過(guò)編程方式自動(dòng)化這一過(guò)程,可以大大提高批量處理 Excel 文件的效率。
環(huán)境準(zhǔn)備
首先需要安裝 Spire.XLS for Python 庫(kù):
pip install Spire.XLS
該庫(kù)提供了豐富的 Excel 操作功能,支持創(chuàng)建、讀取、修改和轉(zhuǎn)換 Excel 文件,無(wú)需安裝 Microsoft Excel。
基礎(chǔ)條件格式設(shè)置
條件格式的核心是根據(jù)設(shè)定的規(guī)則自動(dòng)改變單元格的外觀。最基本的用法是基于數(shù)值范圍應(yīng)用不同的顏色標(biāo)識(shí)。
以下示例演示如何創(chuàng)建一個(gè)工作表,并為數(shù)據(jù)區(qū)域添加條件格式:
from spire.xls import * from spire.xls.common import * # 創(chuàng)建工作簿對(duì)象 workbook = Workbook() # 獲取第一個(gè)工作表 sheet = workbook.Worksheets[0] # 在 A1:C4 區(qū)域插入測(cè)試數(shù)據(jù) sheet.Range["A1"].NumberValue = 582 sheet.Range["A2"].NumberValue = 234 sheet.Range["A3"].NumberValue = 314 sheet.Range["A4"].NumberValue = 50 sheet.Range["B1"].NumberValue = 150 sheet.Range["B2"].NumberValue = 894 sheet.Range["B3"].NumberValue = 560 sheet.Range["B4"].NumberValue = 900 sheet.Range["C1"].NumberValue = 134 sheet.Range["C2"].NumberValue = 700 sheet.Range["C3"].NumberValue = 920 sheet.Range["C4"].NumberValue = 450 # 設(shè)置行高和列寬 sheet.AllocatedRange.RowHeight = 15 sheet.AllocatedRange.ColumnWidth = 17
這段代碼創(chuàng)建了一個(gè)包含 12 個(gè)數(shù)值的工作表區(qū)域。接下來(lái)需要添加條件格式規(guī)則來(lái)突出顯示特定范圍的數(shù)值。
添加多個(gè)條件格式規(guī)則
實(shí)際應(yīng)用中,往往需要同時(shí)應(yīng)用多個(gè)條件規(guī)則。例如,可以用紅色標(biāo)記高于閾值的數(shù)值,用綠色標(biāo)記低于閾值的數(shù)值。
# 創(chuàng)建第一個(gè)條件格式規(guī)則 - 大于 800 的值顯示為紅色
xcfs1 = sheet.ConditionalFormats.Add()
xcfs1.AddRange(sheet.AllocatedRange)
format1 = xcfs1.AddCondition()
format1.FormatType = ConditionalFormatType.CellValue
format1.FirstFormula = "800"
format1.Operator = ComparisonOperatorType.Greater
format1.FontColor = Color.get_Red()
format1.BackColor = Color.get_LightSalmon()
# 創(chuàng)建第二個(gè)條件格式規(guī)則 - 小于 300 的值顯示為綠色
xcfs2 = sheet.ConditionalFormats.Add()
xcfs2.AddRange(sheet.AllocatedRange)
format2 = xcfs1.AddCondition()
format2.FormatType = ConditionalFormatType.CellValue
format2.FirstFormula = "300"
format2.Operator = ComparisonOperatorType.Less
format2.FontColor = Color.get_Green()
format2.BackColor = Color.get_LightBlue()
# 保存文件
workbook.SaveToFile("ApplyConditionalFormatting.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
生成結(jié)果:

上述代碼創(chuàng)建了兩個(gè)條件格式規(guī)則:
- 第一條規(guī)則將大于 800 的單元格字體設(shè)為紅色,背景設(shè)為淺鮭魚色
- 第二條規(guī)則將小于 300 的單元格字體設(shè)為綠色,背景設(shè)為淺藍(lán)色
ConditionalFormats.Add() 方法用于創(chuàng)建新的條件格式集合,AddCondition() 方法添加具體的條件規(guī)則。FormatType 指定條件類型,FirstFormula 設(shè)置比較值,Operator 定義比較操作符。
使用數(shù)據(jù)條進(jìn)行可視化
除了顏色格式,Spire.XLS 還支持?jǐn)?shù)據(jù)條(Data Bars)功能,可以在單元格內(nèi)顯示水平條形圖,直觀地展示數(shù)值大小。
from spire.xls import *
from spire.xls.common import *
workbook = Workbook()
sheet = workbook.Worksheets[0]
# 填充數(shù)據(jù)
for i in range(1, 11):
sheet.Range[f"A{i}"].NumberValue = i * 10
# 添加數(shù)據(jù)條格式
dataBars = sheet.ConditionalFormats.Add()
dataBars.AddRange(sheet.Range["A1:A10"])
dataBarCondition = dataBars.AddCondition()
dataBarCondition.FormatType = ConditionalFormatType.DataBar
dataBarCondition.BarColor = Color.get_Blue()
dataBarCondition.ShowValue = True
workbook.SaveToFile("ApplyDataBarsToCellRange.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
生成結(jié)果:

數(shù)據(jù)條特別適合用于快速比較一系列數(shù)值的大小關(guān)系,無(wú)需創(chuàng)建單獨(dú)的圖表即可實(shí)現(xiàn)可視化效果。
應(yīng)用圖標(biāo)集
圖標(biāo)集(Icon Sets)是另一種直觀的可視化方式,可以在單元格旁邊顯示箭頭、信號(hào)燈、評(píng)級(jí)等圖標(biāo)。
from spire.xls import *
from spire.xls.common import *
workbook = Workbook()
sheet = workbook.Worksheets[0]
# 寫入數(shù)據(jù)
sheet.Range["A1"].NumberValue = 90
sheet.Range["A2"].NumberValue = 75
sheet.Range["A3"].NumberValue = 60
sheet.Range["A4"].NumberValue = 45
sheet.Range["A5"].NumberValue = 30
# 添加圖標(biāo)集
iconSets = sheet.ConditionalFormats.Add()
iconSets.AddRange(sheet.Range["A1:A5"])
iconSetCondition = iconSets.AddCondition()
iconSetCondition.FormatType = ConditionalFormatType.IconSet
iconSetCondition.IconSet.IconSetType = IconSetType.ThreeTrafficLights1
workbook.SaveToFile("ApplyIconSetsToCellRange.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
生成結(jié)果:

圖標(biāo)集適用于分類展示數(shù)據(jù)狀態(tài),例如用紅綠燈圖標(biāo)表示任務(wù)完成狀態(tài)(紅=延遲,黃=進(jìn)行中,綠=完成)。
基于公式的條件格式
更高級(jí)的用法是使用自定義公式來(lái)確定格式應(yīng)用條件。這允許實(shí)現(xiàn)更復(fù)雜的邏輯判斷。
from spire.xls import *
from spire.xls.common import *
workbook = Workbook()
sheet = workbook.Worksheets[0]
# 填充數(shù)據(jù)
sheet.Range["A1"].Value = "姓名"
sheet.Range["B1"].Value = "銷售額"
for i in range(2, 7):
sheet.Range[f"A{i}"].Value = f"員工{i-1}"
sheet.Range[f"B{i}"].NumberValue = (i-1) * 1000
# 使用公式設(shè)置條件格式 - 突出顯示高于平均值的單元格
formulaFormat = sheet.ConditionalFormats.Add()
formulaFormat.AddRange(sheet.Range["B2:B6"])
formulaCondition = formulaFormat.AddCondition()
formulaCondition.FormatType = ConditionalFormatType.Formula
formulaCondition.FirstFormula = "=B2>AVERAGE($B$2:$B$6)"
formulaCondition.FontColor = Color.get_White()
formulaCondition.BackColor = Color.get_DarkGreen()
workbook.SaveToFile("CreateFormulaConditionalFormat.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
生成結(jié)果:

公式條件格式的靈活性在于可以使用任何 Excel 公式作為判斷條件,實(shí)現(xiàn)諸如"標(biāo)記每行的最大值"、"突出顯示重復(fù)值"等復(fù)雜需求。
實(shí)用技巧
組合多種格式效果
在實(shí)際項(xiàng)目中,可以組合使用多種條件格式類型來(lái)增強(qiáng)數(shù)據(jù)表現(xiàn)力:
# 同時(shí)應(yīng)用顏色格式和數(shù)據(jù)條 colors = sheet.ConditionalFormats.Add() colors.AddRange(sheet.Range["A1:D10"]) colorCondition = colors.AddCondition() colorCondition.FormatType = ConditionalFormatType.CellValue colorCondition.Operator = ComparisonOperatorType.Greater colorCondition.FirstFormula = "500" colorCondition.FontColor = Color.get_Red() bars = sheet.ConditionalFormats.Add() bars.AddRange(sheet.Range["A1:D10"]) barCondition = bars.AddCondition() barCondition.FormatType = ConditionalFormatType.DataBar barCondition.BarColor = Color.get_Blue()
動(dòng)態(tài)范圍應(yīng)用
條件格式可以應(yīng)用于動(dòng)態(tài)確定的數(shù)據(jù)范圍,適應(yīng)不同大小的數(shù)據(jù)集:
# 獲取實(shí)際使用的數(shù)據(jù)范圍 usedRange = sheet.AllocatedRange conditionalFormat = sheet.ConditionalFormats.Add() conditionalFormat.AddRange(usedRange)
這種方式確保條件格式始終應(yīng)用于所有包含數(shù)據(jù)的單元格,無(wú)需手動(dòng)指定具體范圍。
總結(jié)
本文介紹了使用 Python 在 Excel 中應(yīng)用條件格式和數(shù)據(jù)可視化的多種方法,包括:
- 基于數(shù)值范圍的單元格格式設(shè)置
- 使用數(shù)據(jù)條展示數(shù)值大小對(duì)比
- 應(yīng)用圖標(biāo)集進(jìn)行分類標(biāo)識(shí)
- 利用自定義公式實(shí)現(xiàn)復(fù)雜條件判斷
- 組合多種格式效果增強(qiáng)可視化
這些技術(shù)可以應(yīng)用于自動(dòng)化報(bào)表生成、數(shù)據(jù)分析儀表板創(chuàng)建、批量 Excel 文件處理等場(chǎng)景。通過(guò)編程方式實(shí)現(xiàn)條件格式的應(yīng)用,不僅提高了工作效率,還確保了格式的一致性和準(zhǔn)確性。
掌握這些技能后,開發(fā)者可以輕松構(gòu)建自動(dòng)化的 Excel 數(shù)據(jù)處理流程,為業(yè)務(wù)分析和決策支持提供有力的技術(shù)支持。
以上就是Python設(shè)置Excel條件格式的實(shí)戰(zhàn)教程的詳細(xì)內(nèi)容,更多關(guān)于Python設(shè)置Excel條件格式的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Pytest單元測(cè)試框架如何實(shí)現(xiàn)參數(shù)化
這篇文章主要介紹了Pytest單元測(cè)試框架如何實(shí)現(xiàn)參數(shù)化,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09
pandas中DataFrame字典互轉(zhuǎn)的實(shí)現(xiàn)
在數(shù)據(jù)處理和分析中,Pandas是一個(gè)非常強(qiáng)大的Python庫(kù),本文主要介紹了pandas中DataFrame字典互轉(zhuǎn)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-04-04
使用Python將字符串轉(zhuǎn)換為格式化的日期時(shí)間字符串
這篇文章主要介紹了使用Python將字符串轉(zhuǎn)換為格式化的日期時(shí)間字符串,需要的朋友可以參考下2019-09-09
python?服務(wù)器批處理得到PSSM矩陣的問(wèn)題
這篇文章主要介紹了python?服務(wù)器批處理得到PSSM矩陣,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07
python判斷鏈表是否有環(huán)的實(shí)例代碼
在本篇文章里小編給大家整理的是關(guān)于python判斷鏈表是否有環(huán)的知識(shí)點(diǎn)及實(shí)例代碼,需要的朋友們參考下。2020-01-01
Python讀取串口數(shù)據(jù)的實(shí)現(xiàn)方法
本文主要介紹了Python讀取串口數(shù)據(jù)的實(shí)現(xiàn)方法,可以使用pySerial庫(kù)來(lái)讀取串口數(shù)據(jù),具有一定的參考價(jià)值,感興趣的可以了解一下2024-02-02
selenium使用chrome瀏覽器測(cè)試(附chromedriver與chrome的對(duì)應(yīng)關(guān)系表)
這篇文章主要介紹了selenium使用chrome瀏覽器測(cè)試(附chromedriver與chrome的對(duì)應(yīng)關(guān)系表),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-11-11

