- Python XlsxWriter 教程
- Python XlsxWriter - 首頁
- Python XlsxWriter - 概述
- Python XlsxWriter - 環境設定
- Python XlsxWriter - Hello World
- Python XlsxWriter - 重要類
- Python XlsxWriter - 單元格表示法和範圍
- Python XlsxWriter - 定義名稱
- Python XlsxWriter - 公式和函式
- Python XlsxWriter - 日期和時間
- Python XlsxWriter - 表格
- Python XlsxWriter - 應用篩選器
- Python XlsxWriter - 字型和顏色
- Python XlsxWriter - 數字格式
- Python XlsxWriter - 邊框
- Python XlsxWriter - 超連結
- Python XlsxWriter - 條件格式
- Python XlsxWriter - 新增圖表
- Python XlsxWriter - 圖表格式
- Python XlsxWriter - 圖表圖例
- Python XlsxWriter - 條形圖
- Python XlsxWriter - 折線圖
- Python XlsxWriter - 餅圖
- Python XlsxWriter - Sparklines
- Python XlsxWriter - 資料驗證
- Python XlsxWriter - 大綱和分組
- Python XlsxWriter - 凍結和拆分窗格
- Python XlsxWriter - 隱藏/保護工作表
- Python XlsxWriter - 文字框
- Python XlsxWriter - 插入圖片
- Python XlsxWriter - 頁面設定
- Python XlsxWriter - 頁首和頁尾
- Python XlsxWriter - 單元格註釋
- Python XlsxWriter - 使用 Pandas
- Python XlsxWriter - VBA 宏
- Python XlsxWriter 有用資源
- Python XlsxWriter - 快速指南
- Python XlsxWriter - 有用資源
- Python XlsxWriter - 討論
Python XlsxWriter - 條件格式
Excel 使用條件格式根據使用者定義的條件更改某個區域中單元格的外觀。從條件格式選單中,可以定義涉及各種型別值的條件。
在下圖所示的工作表中,A 列包含不同的數字。小於 50 的數字顯示為紅色字型和灰色背景色。
這是透過定義以下條件格式規則實現的:
conditional_format() 方法
在 XlsxWriter 中,Worksheet 類中定義了一個conditional_format() 方法。為了實現上述結果,conditional_format() 方法的呼叫方式如下面的程式碼所示:
import xlsxwriter
wb = xlsxwriter.Workbook('hello.xlsx')
ws = wb.add_worksheet()
data=[56,95,63,34,81,47,74,5,99,12]
row=0
for num in data:
ws.write(row,0,num)
row+=1
f1 = wb.add_format({'bg_color': '#D9D9D9', 'font_color': 'red'})
ws.conditional_format(
'A1:A10',{
'type':'cell', 'criteria':'<', 'value':50, 'format':f1
}
)
wb.close()
引數
conditional_format() 方法的第一個引數是單元格區域,第二個引數是條件格式選項的字典。
選項字典使用以下引數配置條件格式規則:
type 選項是必需引數。其值為 cell、date、text、formula 等。每個引數都有子引數,例如 criteria、value、format 等。
Type 是最常見的條件格式型別。當根據簡單條件將格式應用於單元格時,使用此型別。
Criteria 引數設定用於評估單元格資料的條件。除 between 和 not between 運算子外,所有邏輯運算子都是 criteria 引數的可能值。
Value 引數是構成規則的 criteria 的運算元。
Format 引數是 Format 物件(由add_format() 方法返回)。這定義了要應用於滿足條件的單元格的格式功能,例如字型、顏色等。
date 型別類似於 cell 型別,並使用相同的 criteria 和 values。但是,value 引數應作為datetime 物件給出。
text 型別指定 Excel 的“特定文字”樣式條件格式。它用於使用 criteria 和 value 引數執行簡單的字串匹配。
示例
當使用formula 型別時,條件格式取決於使用者定義的公式。
import xlsxwriter
wb = xlsxwriter.Workbook('hello.xlsx')
ws = wb.add_worksheet()
data = [
['Anil', 45, 55, 50], ['Ravi', 60, 70, 80],
['Kiran', 65, 75, 85], ['Karishma', 55, 65, 45]
]
for row in range(len(data)):
ws.write_row(row,0, data[row])
f1 = wb.add_format({'font_color': 'blue', 'bold':True})
ws.conditional_format(
'A1:D4',
{
'type':'formula', 'criteria':'=AVERAGE($B1:$D1)>60', 'value':50, 'format':f1
})
wb.close()
輸出
使用 MS Excel 開啟結果工作簿。我們可以看到滿足上述條件的行根據格式物件顯示為藍色。條件格式規則管理器還顯示了我們在上述程式碼中設定的條件。