Products Technologies Demo Docs Blog Support Company

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.

How to Apply Conditional Formatting in a JavaScript Spreadsheet

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). 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.
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.
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.

Previous: How to Create Pivot Tables in JavaScript
Next: How to Create an ODS File in JavaScript

Frequently Asked Questions

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

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

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

Stay in the loop!

Subscribe to the newsletter to receive the latest updates.

TX Sheet Control

Excel-compatible spreadsheet editing, a robust calculation engine, and interactive dashboards for business applications.

Learn more about TX Sheet Control

Related Posts

JavaScriptExcelJavaScript Spreadsheet Essentials

How to Load REST API Data into a JavaScript Spreadsheet

Fetch REST API JSON into a JavaScript spreadsheet with TX Sheet Control. Validate and map records, show loading and error states, refresh data, and update dependent formulas.


JavaScriptExcelJavaScript Spreadsheet Essentials

How to Create an Excel XLSX File in JavaScript

Create an Excel XLSX file from scratch in JavaScript. Add worksheets, write typed data and formulas, format headers and currency, set column widths, and download the workbook.


JavaScriptExcelJavaScript Spreadsheet Essentials

How to Create an ODS File in JavaScript

Create an ODS workbook in JavaScript with text, numbers, formulas, and currency formatting. Download it, reopen it in TX Sheet Control, and check its standard spreadsheet content in LibreOffice Calc.


JavaScriptExcelJavaScript Spreadsheet Essentials

How to Create Pivot Tables in JavaScript

Create a JavaScript PivotTable from sales records with TX Sheet Control. Configure row and column fields, sum revenue, filter regions, refresh source edits, and export a native Excel PivotTable.


JavaScriptExcelJavaScript Spreadsheet Essentials

How to Export JSON Data to Excel in JavaScript

Export JSON records to a formatted Excel workbook in JavaScript. Map fields, retain numeric values, format dates and currency, calculate totals, and download XLSX.

Share this blog post on:

​​​