使用OpenPyXl
,我们是否可以像在XlsxWriter
data_validation()
中一样拥有特权添加下拉按钮(高和低);并在选择High
时将背景色绿色添加到整行中,如果选择Low
则添加背景色红色?
在XlsxWriter
中,我们有:
format_green = workbook.add_format({'bg_color': 'green'})
format_red = workbook.add_format({'bg_color': 'red'})
# Apply the data validation rule
worksheet.data_validation('D2:D5', {'validate': 'list',
'source': ['High','Low']})
# Apply the conditional formating rules
worksheet.conditional_format('A2:D5', {'type': 'formula',
'criteria': '=$D2="High"',
'format': format_green})
worksheet.conditional_format('A2:D5', {'type': 'formula',
'criteria': '=$D2="Low"',
'format': format_red})
使用OpenPyXl
时,我们有类似的功能吗?
是,Conditional Formatting中同时存在Data Validation和OpenPyXl
。
这里是条件格式的示例:
import openpyxl
from openpyxl import *
from openpyxl.formatting import Rule
from openpyxl.styles import Font, PatternFill, Border, Alignment
from openpyxl.formatting.rule import CellIsRule
wb = load_workbook("./document.xlsx")
ws = wb.active
ws.conditional_formatting.add('A2:D5', CellIsRule(operator='lessThan', formula=['0'],font = Font(color = '00FF0000')))
wb.save('document.xlsx')