# How to Apply Conditional Formatting in a JavaScript Spreadsheet

> Apply conditional formatting in a JavaScript spreadsheet: highlight overdue invoices and negative margins, add revenue data bars and target color scales, and update the rules through cell edits.

- **Author:** Bjoern Meyer
- **Published:** 2026-12-05
- **Modified:** 2026-12-04
- **Description:** Apply conditional formatting in a JavaScript spreadsheet: highlight overdue invoices and negative margins, add revenue data bars and target color scales, and update the rules through cell edits.
- **8 min read** (1500 words)
- **Tags:**
  - JavaScript
  - TX Sheet Control
  - Excel
  - Spreadsheet
  - JavaScript Spreadsheet Essentials
- **Web URL:** https://www.textcontrol.com/blog/2026/12/05/how-to-apply-conditional-formatting-in-a-javascript-spreadsheet/
- **LLMs URL:** https://www.textcontrol.com/blog/2026/12/05/how-to-apply-conditional-formatting-in-a-javascript-spreadsheet/llms.txt
- **LLMs-Full URL:** https://www.textcontrol.com/blog/2026/12/05/how-to-apply-conditional-formatting-in-a-javascript-spreadsheet/llms-full.txt

---

Use conditional formatting to make invoice exceptions and sales performance visible. This JavaScript example combines overdue highlights, negative-margin rules, revenue data bars, a color scale, and a formula-based target comparison.

Part 5 of the JavaScript Spreadsheet Essentials series.

### Run the JavaScript Sample

This example uses TX Sheet Control 2.0.0 with plain JavaScript. [Download the complete sample and output files (ZIP)](https://s1-www.textcontrol.com/assets/dist/blog/2026/12/05/e/assets/javascript-conditional-formatting.zip). Extract it and open its `sample` folder.

Copy the complete `browser` folder from your TX Sheet Control download into `sample/public/sheet`, retaining its fonts, languages, and notices. Put your signed `tx-sheet-control.license` beside `server.mjs`. Use Node.js 22 or later to run the included local host:

```
npm start
```

Open `http://127.0.0.1:5085`. The host serves the files; workbook editing and conversion run in the browser. The HTML supplies the editor host and loads `/sheet/tx-sheet-control.min.js` followed by `app.js`.

The shared `common.js` module creates the editor, awaits its fonts and initial readiness, manages progress messages, and delivers byte downloads:

```
export const { Spreadsheet, StreamType } = TXTextControl.TXSheetControl;
export const status = document.getElementById('status');

export async function createEditor() {
    const response = await fetch('/license', {cache:'no-store'});
    if (!response.ok) throw new Error('Configure tx-sheet-control.license before starting the sample.');
    const editor = new Spreadsheet(document.getElementById('sheet'), {
        license: (await response.text()).trim(),
        fontCatalogURL: '/sheet/fonts/catalog.json',
        fontBaseURL: '/sheet/fonts/', locale:'en-US', currency:'USD'
    });
    await editor.ready;
    return editor;
}

export function download(bytes, name, mime) {
    const url = URL.createObjectURL(new Blob([bytes], {type:mime}));
    const link = document.createElement('a');
    link.href=url; link.download=name;
    document.body.append(link); link.click(); link.remove();
    setTimeout(()=>URL.revokeObjectURL(url),5000);
}

export function showWarnings(warnings) {
    const list=document.getElementById('diagnostics');
    list.replaceChildren();
    const messages=warnings.length ? warnings.map(w=>typeof w==='string' ? w : w.message ?? JSON.stringify(w))
        : ['No conversion warnings.'];
    for(const message of messages) {
        const item=document.createElement('li'); item.textContent=message; list.append(item);
    }
}

export async function busy(message, action) {
    const buttons=[...document.querySelectorAll('button,input[type=file]')];
    buttons.forEach(button=>button.disabled=true);
    status.textContent=message;
    try { return await action(); }
    catch(error) { status.textContent=error.message; throw error; }
    finally { buttons.forEach(button=>button.disabled=false); }
}
```

### Build an Invoice Performance Sheet

The worksheet contains six accounts with Days overdue, Revenue, Cost, Margin, and Target columns. Margin is calculated as `(Revenue - Cost) / Revenue` and displayed as a percentage.

The example uses numeric days overdue supplied by the application. This keeps its results repeatable and avoids changing screenshots with the current date. In an invoice application, derive that number from the due date and your business date policy.

### Add Rules to the Active Worksheet

The workbook-level conditional rule API applies to the active worksheet. This sample creates its report in the initial worksheet. If your application uses another sheet, select it with `editor.ui.selectSheet(sheet)` before adding rules.

```
export function build(workbook) {
    const sheet=workbook.sheets.at(0);
    sheet.rename('Invoice Performance');
    sheet.cell('A1').setText('NORTHSTAR / INVOICE PERFORMANCE');
    sheet.range('A1:F1').merge();
    sheet.cell('A2').setText('Edit days overdue, revenue, cost or target to see the rules update.');
    sheet.range('A4:F10').setValues([
        ['Account','Days overdue','Revenue','Cost','Margin','Target'],
        ['Alpine Retail',12,1200,900,null,1500],
        ['Cedar Partners',0,2400,1600,null,2000],
        ['Northstar Labs',4,3400,2000,null,3000],
        ['Pacific Trading',28,800,950,null,1200],
        ['Riverstone',0,1750,1300,null,1800],
        ['Summit Group',7,1100,1180,null,1400]
    ]);
    for(let row=5;row<=10;row++)sheet.cell(`E${row}`).setFormula(`=(C${row}-D${row})/C${row}`);
    sheet.range('A1:F1').format({fontSize:18,bold:true,textColor:'#762060'});
    sheet.range('A4:F4').format({bold:true,fillColor:'#762060',textColor:'#ffffff'});
    sheet.range('C5:D10').format({numberFormatCode:'$#,##0.00'});
    sheet.range('F5:F10').format({numberFormatCode:'$#,##0.00'});
    sheet.range('E5:E10').format({numberFormatCode:'0.0%'});
    [220,130,150,150,130,150].forEach((pixels,index)=>sheet.columns.at(index).setWidth({pixels}));
    // Workbook-level rule methods apply to the active sheet; this is the initial sheet.
    workbook.addConditionalRule({
        type:'cellIs',ranges:['B5:B10'],operator:'greaterThan',values:[0],
        formatting:{fillColor:'#ffc7ce',textColor:'#9c0006'}
    });
    workbook.addConditionalRule({
        type:'cellIs',ranges:['E5:E10'],operator:'lessThan',values:[0],
        formatting:{fillColor:'#ffc7ce',textColor:'#9c0006'}
    });
    workbook.addConditionalRule({
        type:'dataBar',ranges:['C5:C10'],color:'#14a98b',gradient:false
    });
    workbook.addConditionalRule({
        type:'colorScale',ranges:['F5:F10'],colors:['#f8696b','#ffeb84','#63be7b']
    });
    workbook.addConditionalRule({
        type:'expression',ranges:['C5:C10'],formula:'=C5>=F5',
        formatting:{textColor:'#006100',bold:true}
    });
    return {sheet};
}

export function resolveExceptions(sheet) {
    sheet.cell('B5').setValue(0);
    sheet.cell('D8').setValue(600);
}
```

### Highlight Overdue and Negative Values

A `cellIs` rule on B5:B10 uses `greaterThan` with zero to mark overdue accounts. A second rule on E5:E10 uses `lessThan` with zero to mark negative margins. Both apply a pale red fill and dark red text.

Zero days overdue does not match the first rule. A zero margin does not match the second. Test these exact boundaries, along with blanks and errors, when adapting the rules to your data.

![The initial worksheet highlights overdue accounts and negative margins while comparing revenue and targets.](https://s1-www.textcontrol.com/assets/dist/blog/2026/12/05/e/assets/sample.webp "The initial worksheet highlights overdue accounts and negative margins while comparing revenue and targets.") The initial worksheet highlights overdue accounts and negative margins while comparing revenue and targets.

### Compare Magnitudes with Data Bars and Color Scales

The revenue column receives teal `dataBar` rules with a solid fill. Longer bars identify larger revenue values without replacing the underlying amounts. The Target column uses a three-color scale: low values are red, intermediate values yellow, and high values green within that range.

A relative color scale describes the distribution of values. It does not by itself mean that an account reached a target. The separate expression rule `=C5>=F5` marks revenue values that meet their corresponding targets with green text.

### Watch the Appearance Update

The Resolve two exceptions button sets Alpine's days overdue to zero and reduces Pacific's cost from $950 to $600. Alpine loses its overdue highlight, and Pacific's calculated margin changes from negative to positive.

![After editing the underlying values, the matching conditional appearances update automatically.](https://s1-www.textcontrol.com/assets/dist/blog/2026/12/05/e/assets/conditional-formatting-updated.webp "After editing the underlying values, the matching conditional appearances update automatically.") After editing the underlying values, the matching conditional appearances update automatically.

The cell values and base styles remain separate from the rules. Removing a rule restores the applicable base appearance; it does not clear a cell's contents.

### Wire the Actions and Export

```
import {createEditor,StreamType,download,busy,showWarnings,status} from './common.js';
import {build,resolveExceptions} from './model.js';

async function start(){
 const editor=await createEditor();
 const actions={};let model={};
 const addAction=(id,label,action)=>{
  actions[id]=action;const button=document.createElement('button');button.id=id;button.textContent=label;
  button.addEventListener('click',()=>busy('Working…',action).catch(()=>{}));
  document.getElementById('actions').append(button);
 };
 const downloadXlsx=async()=>{
  const bytes=await editor.save(StreamType.SpreadsheetML);
  showWarnings(editor.getXlsxWarnings());
  download(bytes,'conditional-formatting.xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  status.textContent='Workbook exported successfully. Review conversion diagnostics.';
 };
 model=build(editor.workbook);
 addAction('resolve','Resolve two exceptions',async()=>{resolveExceptions(model.sheet);status.textContent='Alpine is no longer overdue; Pacific margin is now positive.';});
 addAction('export','Download formatted XLSX',downloadXlsx);
 status.textContent='Red: overdue or negative margin · Teal bars: revenue · Color scale: target.';
 return {editor,actions,get model(){return model;}};
}
window.sampleReady=start();
window.sampleReady.catch(error=>{status.textContent=error.message;console.error(error);});
```

Use the Home ribbon's Conditional Formatting menu to review or edit the rules. Manage Rules shows their ranges and order. The API also returns stable IDs from `addConditionalRule()`, which you can use with `updateConditionalRule()` or `deleteConditionalRule()`.

Save the workbook as XLSX to exchange supported native conditional definitions with Excel. Check the exported appearance and definitions for the rules your application relies on, particularly when importing specialized Excel-authored rules.

Read more in the [TX Sheet Control documentation](https://docs.textcontrol.com/tx-sheet-control/spreadsheets/conditional-formatting/).

[Previous: How to Create Pivot Tables in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-create-pivot-tables-in-javascript/llms-full.txt)  
[Next: How to Create an ODS File in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-create-an-ods-file-in-javascript/llms-full.txt)

JavaScript Spreadsheet Essentials · Part 5 of 8

1. [How to Import, Edit, and Export Excel XLSX Files in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-import-edit-and-export-excel-xlsx-files-in-javascript/llms-full.txt)
2. [How to Convert Excel to PDF in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-convert-excel-to-pdf-in-javascript/llms-full.txt)
3. [How to Export JSON Data to Excel in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-export-json-data-to-excel-in-javascript/llms-full.txt)
4. [How to Create Pivot Tables in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-create-pivot-tables-in-javascript/llms-full.txt)
5. How to Apply Conditional Formatting in a JavaScript Spreadsheet
6. [How to Create an ODS File in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-create-an-ods-file-in-javascript/llms-full.txt)
7. [How to Create an Excel XLSX File in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-create-an-excel-xlsx-file-in-javascript/llms-full.txt)
8. [How to Load REST API Data into a JavaScript Spreadsheet](https://www.textcontrol.com/blog/2026/12/05/how-to-load-rest-api-data-into-a-javascript-spreadsheet/llms-full.txt)

### Frequently Asked Questions

Does a rule overwrite the cell value? 
--------------------------------------

No. Conditional formatting calculates an appearance while preserving cell values and formulas.

Do the rules update when users edit cells? 
-------------------------------------------

Yes. Changing a value or a dependent formula result recalculates the matching appearance.

Does green in a color scale mean the sales target was reached? 
---------------------------------------------------------------

Not necessarily. The scale compares values within its range. Use an explicit formula or threshold rule to represent target attainment.

---

## About Bjoern Meyer

As CEO, Bjoern is the visionary behind our strategic direction and business development, bridging the gap between our customers and engineering teams. His deep passion for coding and web technologies drives the creation of innovative products. If you're at a tech conference, be sure to stop by our booth - you'll most likely meet Bjoern in person. With an advanced graduate degree (Dipl. Inf.) in Computer Science, specializing in AI, from the University of Bremen, Bjoern brings significant expertise to his role. In his spare time, Bjoern enjoys running, paragliding, mountain biking, and playing the piano.

- [LinkedIn](https://www.linkedin.com/in/bjoernmeyer/)
- [X](https://x.com/txbjoern)
- [GitHub](https://github.com/bjoerntx)

---

## Series

- [How to Import, Edit, and Export Excel XLSX Files in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-import-edit-and-export-excel-xlsx-files-in-javascript/llms.txt)
- [How to Convert Excel to PDF in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-convert-excel-to-pdf-in-javascript/llms.txt)
- [How to Export JSON Data to Excel in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-export-json-data-to-excel-in-javascript/llms.txt)
- [How to Create Pivot Tables in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-create-pivot-tables-in-javascript/llms.txt)
- **How to Apply Conditional Formatting in a JavaScript Spreadsheet** (this article)
- [How to Create an ODS File in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-create-an-ods-file-in-javascript/llms.txt)
- [How to Create an Excel XLSX File in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-create-an-excel-xlsx-file-in-javascript/llms.txt)
- [How to Load REST API Data into a JavaScript Spreadsheet](https://www.textcontrol.com/blog/2026/12/05/how-to-load-rest-api-data-into-a-javascript-spreadsheet/llms.txt)

---

## Related Posts

- [How to Load REST API Data into a JavaScript Spreadsheet](https://www.textcontrol.com/blog/2026/12/05/how-to-load-rest-api-data-into-a-javascript-spreadsheet/llms.txt)
- [How to Create an Excel XLSX File in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-create-an-excel-xlsx-file-in-javascript/llms.txt)
- [How to Create an ODS File in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-create-an-ods-file-in-javascript/llms.txt)
- [How to Create Pivot Tables in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-create-pivot-tables-in-javascript/llms.txt)
- [How to Export JSON Data to Excel in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-export-json-data-to-excel-in-javascript/llms.txt)
- [How to Convert Excel to PDF in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-convert-excel-to-pdf-in-javascript/llms.txt)
- [How to Import, Edit, and Export Excel XLSX Files in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-import-edit-and-export-excel-xlsx-files-in-javascript/llms.txt)
- [Inside the TX Sheet Control Spreadsheet Editor: A Complete Spreadsheet for Your Web Applications](https://www.textcontrol.com/blog/2026/12/01/inside-the-tx-sheet-control-spreadsheet-editor/llms.txt)
- [TX Sheet Control 2.0 Is Now Available: Spreadsheets and Dashboards for Your Applications](https://www.textcontrol.com/blog/2026/12/01/tx-sheet-control-2-0-is-now-available/llms.txt)
