可以通过代码(不是 Excel 中的 FC)在 Excel-Xlwings 中的数学条件下更改列的颜色。我的意思是,用桌子:
姓名 | 投票 |
---|---|
罗西 | 5 |
比安奇 | 7 |
威尔第 | 8 |
内里 | 4 |
我想建立一个投票数低于6的图表(如果投票<6) , Rossi and Neri, in RED color, the others in GREEN. Thank you.
以下是使用 Xlwings 对 B2:B5 范围内的数据实现条件格式的代码。
该代码还创建工作簿并写入示例数据。
import xlwings as xw
from xlwings import constants
import pandas as pd
from xlwings.utils import rgb_to_int
with xw.App(visible=True) as xl:
# Create a sample DataFrame
df = pd.DataFrame({
'Name': ['Rossi', 'Bianchi', 'Verdi', 'Neri'],
'Vote': [5, 7, 8, 4]
})
wb = xw.Book()
ws = wb.sheets["Sheet1"]
ws.range('A1').options(index=False).value = df
ws.range("A1:B1").Bold = True
### Cells to include in the Conditional Formatting range
cf_range = ws.range('B2:B5')
### Create CF Rule for values less than 6 Fill Red
cf1 = cf_range.api.FormatConditions.Add(
Type=constants.FormatConditionType.xlCellValue,
Operator=constants.FormatConditionOperator.xlLess,
Formula1=6
)
cf_range.api.FormatConditions(1).Interior.PatternColorIndex = constants.Constants.xlAutomatic
cf_range.api.FormatConditions(1).Interior.Color = rgb_to_int((255, 0, 0))
cf_range.api.FormatConditions(1).StopIfTrue = False
### Create CF Rule for values greater and equal to 6 Fill Green
cf2 = cf_range.api.FormatConditions.Add(
Type=constants.FormatConditionType.xlCellValue,
Operator=constants.FormatConditionOperator.xlGreaterEqual,
Formula1=6
)
ws.range('B2:B5').api.FormatConditions(2).Interior.PatternColorIndex = constants.Constants.xlAutomatic
ws.range('B2:B5').api.FormatConditions(2).Interior.Color = rgb_to_int((0, 255, 0))
ws.range('B2:B5').api.FormatConditions(2).StopIfTrue = False
wb.save('cf_example.xlsx')