Add conditional formatting
Use this page to add Excel conditional-format rules to a sheet and to find out what they do to each cell, for example to paint a grid or to check a file before sending it. The engine evaluates the rules; it does not paint cells. Conditional formats lists every rule type and option, and the calls are in the WASM API and the Python API.
Highlight cells that meet a condition
A highlight rule points at a differential format: a partial style in the workbook's dxf table. Register it with wb.ooxml.addDxf(), then add the rule with ws.addCfRule(), which returns the rule's id. A CellIs rule compares each cell's value; an Expression rule is a formula written for the top-left cell of the range, and its relative references shift for the other cells. Give a solid fill both foreground and background, because Excel paints a differential fill from its background colour.
import createFormulon, { CfRuleType, ComparisonOperator, FillPattern } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('A1', [['Item', 'Stock'], ['Bolts', 40], ['Nuts', 75], ['Washers', 0]])
const red = wb.ooxml.addDxf({ fill: { pattern: FillPattern.Solid, foreground: '#FFC7CE', background: '#FFC7CE' } })
const bold = wb.ooxml.addDxf({ font: { bold: true } })
const low = ws.addCfRule({
ranges: 'B2:B4',
type: CfRuleType.CellIs,
operator: ComparisonOperator.LessThan,
formula1: '50',
dxfIndex: red,
})
ws.addCfRule({ ranges: 'A2:B4', type: CfRuleType.Expression, formula1: '$B2=0', dxfIndex: bold })
console.log(ws.getCfRule(low).formula1) // =50
const hits = ws.evaluateCfRange('A2:B4')
console.log(hits.map((c) => `${c.row},${c.col}`).join(' ')) // 1,1 3,0 3,1
} finally {
wb.dispose()
}from formulon import (
CfCellIsRuleInput,
CfExpressionRuleInput,
ComparisonOperator,
DxfInput,
Fill,
FillPattern,
Font,
Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [["Item", "Stock"], ["Bolts", 40], ["Nuts", 75], ["Washers", 0]])
red = wb.ooxml.add_dxf(DxfInput(fill=Fill(pattern=FillPattern.SOLID, foreground="#FFC7CE", background="#FFC7CE")))
bold = wb.ooxml.add_dxf(DxfInput(font=Font(bold=True)))
low = ws.add_cf_rule(CfCellIsRuleInput(
ranges="B2:B4",
operator=ComparisonOperator.LESS_THAN,
formula1="50",
dxf_index=red,
))
ws.add_cf_rule(CfExpressionRuleInput(ranges="A2:B4", formula1="$B2=0", dxf_index=bold))
print(ws.get_cf_rule(low).formula1) # =50
hits = ws.evaluate_cf_range("A2:B4")
print(" ".join(f"{c.row},{c.col}" for c in hits)) # 1,1 3,0 3,1evaluateCfRange returns only the cells that at least one rule matched. Top/bottom N, above average, text, blanks, errors, dates and duplicate rules work the same way with their own CfRuleType.
Add a colour scale
A colour scale takes two or three thresholds and as many colours. A threshold is a value object: Min and Max take no value, while Number, Percent, Percentile and Formula take a value string. The match for each cell carries the interpolated colour as a Color whose argb is 0xAARRGGBB.
import createFormulon, { CfRuleType, CfValueObjectType } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('A1', [[10], [40], [70], [100]])
ws.addCfRule({
ranges: 'A1:A4',
type: CfRuleType.ColorScale,
colorScale: {
thresholds: [{ type: CfValueObjectType.Min }, { type: CfValueObjectType.Max }],
colors: ['#F8696B', '#63BE7B'],
},
})
const hex = (color) => (color.argb & 0xffffff).toString(16).padStart(6, '0')
const cells = ws.evaluateCfRange('A1:A4')
console.log(cells.map((c) => hex(c.matches[0].color)).join()) // f8696b,c68570,95a276,63be7b
} finally {
wb.dispose()
}from formulon import (
CfColorScaleInput,
CfColorScaleRuleInput,
CfValueObject,
CfValueObjectType,
Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [[10], [40], [70], [100]])
ws.add_cf_rule(CfColorScaleRuleInput(
ranges="A1:A4",
color_scale=CfColorScaleInput(
[CfValueObject(CfValueObjectType.MIN), CfValueObject(CfValueObjectType.MAX)],
["#F8696B", "#63BE7B"],
),
))
cells = ws.evaluate_cf_range("A1:A4")
print(",".join(format(c.matches[0].color.argb & 0xFFFFFF, "06x") for c in cells)) # f8696b,c68570,95a276,63be7bAdd data bars
A data bar takes min and max thresholds and a fill colour. The match gives the bar's length and the axis position as percentages of the cell width, measured from the left edge. Bars run from 10% to 90% of the cell by default; minLengthPct and maxLengthPct change that.
import createFormulon, { CfRuleType, CfValueObjectType } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('A1', [[10], [40], [70], [100]])
ws.addCfRule({
ranges: 'A1:A4',
type: CfRuleType.DataBar,
dataBar: { min: { type: CfValueObjectType.Min }, max: { type: CfValueObjectType.Max }, fill: '#638EC6' },
})
const lengths = ws.evaluateCfRange('A1:A4').map((c) => c.matches[0].bar.lengthPct.toFixed(1))
console.log(lengths.join()) // 10.0,36.7,63.3,90.0
} finally {
wb.dispose()
}from formulon import CfDataBarInput, CfDataBarRuleInput, CfValueObject, CfValueObjectType, Workbook
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [[10], [40], [70], [100]])
ws.add_cf_rule(CfDataBarRuleInput(
ranges="A1:A4",
data_bar=CfDataBarInput(
min=CfValueObject(CfValueObjectType.MIN),
max=CfValueObject(CfValueObjectType.MAX),
fill="#638EC6",
),
))
lengths = [f"{c.matches[0].bar.length_pct:.1f}" for c in ws.evaluate_cf_range("A1:A4")]
print(",".join(lengths)) # 10.0,36.7,63.3,90.0Negative values, a gradient or solid fill, borders and the axis position are options of the same dataBar record.
Add an icon set
An icon set takes a set name and one threshold fewer than it has icons: ThreeArrows takes two. The match gives the iconIndex, counted from 0 for the lowest bucket, and the host draws the icon for that level.
import createFormulon, { CfRuleType, CfValueObjectType, IconSetName } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('A1', [[10], [40], [70], [100]])
ws.addCfRule({
ranges: 'A1:A4',
type: CfRuleType.IconSet,
iconSet: {
name: IconSetName.ThreeArrows,
thresholds: [
{ type: CfValueObjectType.Percent, value: '33' },
{ type: CfValueObjectType.Percent, value: '67' },
],
},
})
const icons = ws.evaluateCfRange('A1:A4').map((c) => c.matches[0].icon.iconIndex)
console.log(icons.join()) // 0,1,1,2
} finally {
wb.dispose()
}from formulon import (
CfIconSetInput,
CfIconSetRuleInput,
CfValueObject,
CfValueObjectType,
IconSetName,
Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [[10], [40], [70], [100]])
ws.add_cf_rule(CfIconSetRuleInput(
ranges="A1:A4",
icon_set=CfIconSetInput(
IconSetName.THREE_ARROWS,
[CfValueObject(CfValueObjectType.PERCENT, "33"), CfValueObject(CfValueObjectType.PERCENT, "67")],
),
))
icons = [c.matches[0].icon.icon_index for c in ws.evaluate_cf_range("A1:A4")]
print(icons) # [0, 1, 1, 2]Find the cells each rule hits
Each match in evaluateCfRange carries its kind (CfMatchKind) and the priority of the rule that produced it, and a cell lists its matches in priority order. listCfRules() gives each rule's priority, so a host can map a match back to its rule. stopIfTrue on a rule ends evaluation for a cell it matches, so lower-priority rules do not appear there. evaluateCfFormula(cell, anchor, formula) tests a formula the way an Expression rule anchored at anchor would, without adding a rule.
import createFormulon, { CfRuleType, ComparisonOperator, FillPattern } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('A1', [[40], [75], [90], [60]])
const red = wb.ooxml.addDxf({ fill: { pattern: FillPattern.Solid, foreground: '#FFC7CE', background: '#FFC7CE' } })
const green = wb.ooxml.addDxf({ fill: { pattern: FillPattern.Solid, foreground: '#C6EFCE', background: '#C6EFCE' } })
ws.addCfRule({
ranges: 'A1:A4', type: CfRuleType.CellIs, operator: ComparisonOperator.GreaterThan,
formula1: '80', dxfIndex: red, stopIfTrue: true,
})
ws.addCfRule({
ranges: 'A1:A4', type: CfRuleType.CellIs, operator: ComparisonOperator.GreaterThan,
formula1: '50', dxfIndex: green,
})
const byPriority = new Map(ws.listCfRules().map((r) => [r.priority, r.formula1]))
const hits = ws.evaluateCfRange('A1:A4')
const describe = (cell) => `A${cell.row + 1} ${cell.matches.map((m) => byPriority.get(m.priority)).join(' ')}`
console.log(hits.map(describe).join(', ')) // A2 =50, A3 =80, A4 =50
console.log(ws.evaluateCfFormula('A2', 'A1', 'A1>70')) // true
} finally {
wb.dispose()
}from formulon import CfCellIsRuleInput, ComparisonOperator, DxfInput, Fill, FillPattern, Workbook
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [[40], [75], [90], [60]])
red = wb.ooxml.add_dxf(DxfInput(fill=Fill(pattern=FillPattern.SOLID, foreground="#FFC7CE", background="#FFC7CE")))
green = wb.ooxml.add_dxf(DxfInput(fill=Fill(pattern=FillPattern.SOLID, foreground="#C6EFCE", background="#C6EFCE")))
ws.add_cf_rule(CfCellIsRuleInput(
ranges="A1:A4", operator=ComparisonOperator.GREATER_THAN,
formula1="80", dxf_index=red, stop_if_true=True,
))
ws.add_cf_rule(CfCellIsRuleInput(
ranges="A1:A4", operator=ComparisonOperator.GREATER_THAN,
formula1="50", dxf_index=green,
))
by_priority = {r.priority: r.formula1 for r in ws.list_cf_rules()}
hits = ws.evaluate_cf_range("A1:A4")
def describe(cell):
return f"A{cell.row + 1} " + " ".join(by_priority[m.priority] for m in cell.matches)
print(", ".join(describe(c) for c in hits)) # A2 =50, A3 =80, A4 =50
print(ws.evaluate_cf_formula("A2", "A1", "A1>70")) # TrueThe engine does not merge a matched differential format into the cell's style. A host that draws cells lays the dxf record (wb.ooxml.getDxf(index)) over the cell's own style itself.
Read, change and remove rules
listCfRules() returns every rule on the sheet with its id, type, ranges and settings, and a rule read back can be passed to addCfRule unchanged on another sheet, or with its id cleared on the same sheet, which refuses an id it already holds with StatusCode.AlreadyExists. getCfRule, updateCfRule and removeCfRule take the rule's id or its position in the list. A position moves when a rule is added or removed; an id does not. setCfRulePriority(cfRule, priority) gives a rule a priority and raises the number of every other rule at or above it by one.
import createFormulon, { CfRuleType, ComparisonOperator, FillPattern, enumName } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('A1', [[40], [75], [90], [60]])
const red = wb.ooxml.addDxf({ fill: { pattern: FillPattern.Solid, foreground: '#FFC7CE', background: '#FFC7CE' } })
const id = ws.addCfRule({
ranges: 'A1:A4', type: CfRuleType.CellIs, operator: ComparisonOperator.GreaterThan,
formula1: '70', dxfIndex: red,
})
const [rule] = ws.listCfRules()
console.log(enumName(CfRuleType, rule.type), JSON.stringify(rule.ranges[0])) // CellIs {"firstRow":0,"firstCol":0,"lastRow":3,"lastCol":0}
ws.updateCfRule(id, { formula1: '80' })
console.log(ws.evaluateCfRange('A1:A4').length) // 1
ws.removeCfRule(id)
console.log(ws.listCfRules().length) // 0
} finally {
wb.dispose()
}from formulon import (
CfCellIsRuleInput,
CfRuleType,
ComparisonOperator,
DxfInput,
Fill,
FillPattern,
Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [[40], [75], [90], [60]])
red = wb.ooxml.add_dxf(DxfInput(fill=Fill(pattern=FillPattern.SOLID, foreground="#FFC7CE", background="#FFC7CE")))
rule_id = ws.add_cf_rule(CfCellIsRuleInput(
ranges="A1:A4", operator=ComparisonOperator.GREATER_THAN,
formula1="70", dxf_index=red,
))
rule = ws.list_cf_rules()[0]
print(CfRuleType(rule.type).name, rule.ranges[0]) # CELL_IS CellRect(first_row=0, first_col=0, last_row=3, last_col=0)
ws.update_cf_rule(rule_id, formula1="80")
print(len(ws.evaluate_cf_range("A1:A4"))) # 1
ws.remove_cf_rule(rule_id)
print(len(ws.list_cf_rules())) # 0Rules are saved with the workbook, and rules Excel stores in its x14 extension (custom icon sets, data bar options) load as one rule each.