FreeGridv1.6.0한국어

Conditional formatting

Colour cells by value or formula, highlight the top and bottom values, averages and duplicates, and draw data bars, colour scales and icon sets that carry into Excel, print and PDF.

Live demoConditional formatting

Colour cells by value or formula, top and bottom ranks, duplicates, data bars, colour scales and icon sets.

Code for this demo
import { createGrid, type ConditionalFormat } from '@freegridjs/core';
import { HEADERS, makeRows } from '../data';
import { button, separator, text, toggle, tr, type DemoContext } from '../ui';

export default function mount(ctx: DemoContext) {
  const { lang } = ctx;
  const h = (en: string, ko: string) => tr(lang, { en, ko });
  const t = HEADERS[lang];
  const rules: Record<string, ConditionalFormat> = {
    // a colour by value, for the whole row
    closed: { columns: ['status'], row: true, op: 'eq', value: 'Closed', style: { color: '#9ca3af', italic: true } },
    q1: { columns: ['q1'], type: 'dataBar', color: '#3b82f6' },
    q2: { columns: ['q2'], type: 'colorScale', colors: ['#f8696b', '#ffeb84', '#63be7b'] },
    growth: { columns: ['growth'], type: 'iconSet', icons: 'arrows' },
    top: { columns: ['total'], type: 'top', rank: 5, style: { background: '#c6efce', color: '#006100', bold: true } },
    low: { columns: ['total'], op: 'lt', value: 120000, style: { background: '#ffc7ce', color: '#9c0006' } },
    dup: { columns: ['company'], type: 'duplicate', style: { background: '#fff4ce' } },
    formula: { columns: ['name'], type: 'formula', formula: '=AND(active, growth > 0.2)', style: { bold: true, color: '#1d4ed8' } },
  };
  const on = new Set(['closed', 'q1', 'q2', 'growth', 'top', 'low']);
  const grid = createGrid(ctx.host, {
    columns: [
      { field: 'name', header: t.name, width: 150 },
      { field: 'company', header: t.company, width: 130 },
      { field: 'q1', header: t.q1, type: 'number', format: '#,##0', width: 110 },
      { field: 'q2', header: t.q2, type: 'number', format: '#,##0', width: 110 },
      { field: 'growth', header: t.growth, type: 'number', format: '0.0%', width: 100 },
      { field: 'total', header: t.total, type: 'number', format: '#,##0', width: 120 },
      { field: 'active', header: t.active, type: 'boolean', width: 70 },
      { field: 'status', header: t.status, width: 100 },
    ],
    data: makeRows(200), locale: lang, getRowId: r => String(r.id),
    conditionalFormats: [...on].map(k => rules[k]),
  });
  const apply = () => grid.setConditionalFormats([...on].map(k => rules[k]));
  grid.on('conditionalFormatsChange', e => ctx.log(`conditionalFormatsChange → ${e.formats.length} ${h('rules', '개 규칙')}`));

  text(ctx, h('Turn rules on and off. The column menu (⋮) → Conditional formatting… adds rules by hand; Excel and print keep the colours.',
    '규칙을 켜고 꺼 보세요. 컬럼 메뉴(⋮) → 조건부 서식…에서 직접 규칙을 추가할 수 있고, 엑셀·인쇄에도 색이 그대로 나갑니다.'));
  separator(ctx);
  const labels: [string, string, string][] = [
    ['q1', 'Data bars', '데이터 막대'], ['q2', 'Colour scale', '색조'], ['growth', 'Icons', '아이콘'], ['top', 'Top 5', '상위 5'],
    ['low', 'Below 120,000', '12만 미만'], ['dup', 'Duplicates', '중복 값'], ['closed', 'Closed rows', '종료 행'], ['formula', 'Formula rule', '수식 규칙'],
  ];
  for (const [k, en, ko] of labels) {
    toggle(ctx, h(en, ko), on.has(k), v => {
      if (v) on.add(k);
      else on.delete(k);
      apply();
    });
  }
  separator(ctx);
  button(ctx, h('Rules for Total…', '합계 규칙 편집…'), () => grid.openConditionalFormats('total'));
  button(ctx, h('Export Excel', '엑셀로 내보내기'), () => grid.exportXlsx(h('formats.xlsx', '조건부서식.xlsx')));
  return grid;
}

Conditional formats colour cells, make them bold, or draw bars and icons from their values, the way spreadsheets do, so people need no explanation. People add rules from the column menu (⋮) → Conditional formatting…; in code they go in the conditionalFormats option. Formats follow live updates and carry into Excel, print and PDF.

createGrid(el, {
  columns, data,
  conditionalFormats: [
    // by value: sales of 100M or more in green
    { columns: ['sales'], op: 'gte', value: 100000000, style: { background: '#c6efce', color: '#006100', bold: true } },
    // by formula: the whole row in red when below target
    { columns: ['sales'], type: 'formula', formula: '=sales < target', row: true, style: { color: '#dc2626' } },
    // the top 10, duplicate values
    { columns: ['score'], type: 'top', rank: 10, style: { background: '#fff4ce' } },
    { columns: ['email'], type: 'duplicate', style: { background: '#ffc7ce' } },
    // data bars, colour scales and icons
    { columns: ['progress'], type: 'dataBar', color: '#3b82f6', min: 0, max: 100 },
    { columns: ['temperature'], type: 'colorScale', colors: ['#5b8def', '#ffffff', '#f8696b'] },
    { columns: ['growth'], type: 'iconSet', icons: 'arrows' },
  ],
});

Rule types

Rules apply top to bottom, and a later rule wins for the same property. Top, average, duplicates, bars, scales and icons look at the rows left after filtering.

NameTypeDescription
'value'op: 'gt' | 'gte' | 'lt' | 'lte' | 'eq' | 'ne' | 'between' | 'notBetween' | 'contains' | 'notContains' | 'startsWith' | 'endsWith' | 'blank' | 'notBlank'Compare the cell with value (and valueTo). The default type.
'formula'formula: '=amount > target'A formula over the row; true applies the style.
'top' / 'bottom'rank?: number, percent?: booleanThe highest or lowest n values (or n %) of the column.
'aboveAverage' / 'belowAverage'—Above or below the column average.
'duplicate' / 'unique'—Values that appear more than once, or once.
'dataBar'color?, min?, max?A bar in the cell, as long as the value; negative numbers grow from zero.
'colorScale'colors?: ['#f8696b', '#ffeb84', '#63be7b']Two or three colours from the lowest to the highest value.
'iconSet'icons?: 'arrows' | 'traffic' | 'signs'An icon for the top, middle and bottom third.
style{ color?, background?, bold?, italic?, strike? }The look of matching cells. row: true styles the whole row; stopIfTrue stops later rules.

API and saving

Rules are plain objects you can store as JSON, and getState() includes them, so they save and restore with each person's view. conditionalFormatMenu: false hides the column menu item.

grid.setConditionalFormats([...grid.getConditionalFormats(), { columns: ['qty'], op: 'lt', value: 0, style: { color: 'red' } }]);
grid.openConditionalFormats('qty');                  // the dialog for one column
grid.on('conditionalFormatsChange', e => save(e.formats));
const state = grid.getState();                       // saved views include the formats

Colours can be #hex, rgb(), hsl() or names. Excel exports carry #hex colours into the cell styles.

Questions about this page

How do I highlight cells by value in FreeGrid?

Add a rule to the conditionalFormats option, for example { columns: ["sales"], op: "gte", value: 1000, style: { background: "#c6efce" } }, or use Conditional formatting… in the column menu.

Does FreeGrid support data bars and colour scales?

Yes: type "dataBar", "colorScale" and "iconSet" rules draw bars, colour gradients and arrow or traffic-light icons, and they carry into Excel, print and PDF.