조건부 서식
값이나 수식으로 셀 색을 바꾸고 상위·하위, 평균, 중복 값을 강조하며, 데이터 막대·색조·아이콘 집합을 그립니다. 엑셀·인쇄·PDF에도 그대로 나갑니다.
실행 예제조건부 서식
값이나 수식으로 셀 색을 바꾸고, 상위·하위, 중복, 데이터 막대, 색조, 아이콘 집합을 표시합니다.
이 데모의 코드
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;
}조건부 서식은 셀 값에 따라 색, 굵기, 막대, 아이콘을 자동으로 붙입니다. 엑셀의 조건부 서식과 같은 방식이라 사용자에게 설명할 필요가 거의 없습니다. 사용자는 컬럼 메뉴(⋮)의 조건부 서식…에서 직접 규칙을 만들 수 있고, 코드에서는 conditionalFormats 옵션으로 줍니다. 서식은 실시간 업데이트를 따라가고, 엑셀 내보내기·인쇄·PDF에도 그대로 나갑니다.
createGrid(el, {
columns, data,
conditionalFormats: [
// 값 비교: 매출 1억 이상은 초록
{ columns: ['sales'], op: 'gte', value: 100000000, style: { background: '#c6efce', color: '#006100', bold: true } },
// 수식: 목표 미달이면 행 전체를 빨강 글자로
{ columns: ['sales'], type: 'formula', formula: '=sales < target', row: true, style: { color: '#dc2626' } },
// 상위 10개, 중복 값
{ columns: ['score'], type: 'top', rank: 10, style: { background: '#fff4ce' } },
{ columns: ['email'], type: 'duplicate', style: { background: '#ffc7ce' } },
// 데이터 막대, 색조, 아이콘
{ columns: ['progress'], type: 'dataBar', color: '#3b82f6', min: 0, max: 100 },
{ columns: ['temperature'], type: 'colorScale', colors: ['#5b8def', '#ffffff', '#f8696b'] },
{ columns: ['growth'], type: 'iconSet', icons: 'arrows' },
],
});규칙 종류
규칙은 위에서 아래로 적용되고, 같은 속성은 뒤 규칙이 이깁니다. 상위·평균·중복·막대·색조·아이콘은 필터를 거친 행을 기준으로 계산합니다.
| 이름 | 타입 | 설명 |
|---|---|---|
'value' | op: 'gt' | 'gte' | 'lt' | 'lte' | 'eq' | 'ne' | 'between' | 'notBetween' | 'contains' | 'notContains' | 'startsWith' | 'endsWith' | 'blank' | 'notBlank' | 셀 값을 value(와 valueTo)와 비교합니다. 기본 종류입니다. |
'formula' | formula: '=amount > target' | 행에 대한 수식이 참이면 서식을 적용합니다. |
'top' / 'bottom' | rank?: number, percent?: boolean | 컬럼에서 가장 큰(작은) n개, 또는 n%. |
'aboveAverage' / 'belowAverage' | — | 컬럼 평균보다 크거나 작은 값. |
'duplicate' / 'unique' | — | 두 번 이상 나오는 값, 한 번만 나오는 값. |
'dataBar' | color?, min?, max? | 값 크기만큼 셀 안에 막대를 그립니다. 음수는 0에서 반대로 그립니다. |
'colorScale' | colors?: ['#f8696b', '#ffeb84', '#63be7b'] | 가장 작은 값부터 큰 값까지 두세 가지 색으로 칠합니다. |
'iconSet' | icons?: 'arrows' | 'traffic' | 'signs' | 위·가운데·아래 3분의 1에 각각 아이콘을 붙입니다. |
style | { color?, background?, bold?, italic?, strike? } | 조건에 맞는 셀의 모양. row: true면 행 전체, stopIfTrue면 뒤 규칙을 적용하지 않습니다. |
API와 저장
규칙은 일반 객체라 JSON으로 저장할 수 있습니다. getState()에도 들어가므로 사용자별 화면 설정과 함께 저장하고 복원하세요. 컬럼 메뉴의 항목을 숨기려면 conditionalFormatMenu: false를 주세요.
grid.setConditionalFormats([...grid.getConditionalFormats(), { columns: ['qty'], op: 'lt', value: 0, style: { color: 'red' } }]);
grid.openConditionalFormats('qty'); // 컬럼의 조건부 서식 창
grid.on('conditionalFormatsChange', e => save(e.formats));
const state = grid.getState(); // 저장한 화면 설정에도 들어갑니다색은 #hex, rgb(), hsl(), 색 이름을 쓸 수 있습니다. 엑셀로 내보낼 때는 #hex 색이 셀 서식으로 들어갑니다.
이 페이지에 대한 질문
값에 따라 셀 색을 바꾸려면 어떻게 하나요?
conditionalFormats 옵션에 { columns: ["sales"], op: "gte", value: 1000, style: { background: "#c6efce" } } 같은 규칙을 넣거나, 컬럼 메뉴의 조건부 서식…에서 추가하면 됩니다.
데이터 막대나 색조도 되나요?
네. "dataBar", "colorScale", "iconSet" 규칙으로 막대, 색 그라데이션, 화살표·신호등 아이콘을 그리며, 엑셀·인쇄·PDF에도 그대로 나갑니다.