Apply Conditional Formatting in Worksheets
This article is designed to provide a detailed understanding of how to add conditional formatting to a range of cells in a worksheet.
Conditional formatting is an advanced feature in Microsoft Excel that allows you to apply formats to a range of cells, and have that formatting change depending on the value of the cell or the value of a formula. For example, the background of a cell may be red to highlight a negative value, or the text color might be green for a positive value. When the value of the cell meets the format condition, the format is applied. If the value of the cell does not meet the format condition, the cell’s default formatting is used.
It’s possible to apply conditional formatting with Microsoft Office Automation but that has its drawbacks. There are several reasons and issues involved: for example, security, stability, scalability and speed. The main reason for finding another solution is that Microsoft themselves strongly recommends against Office Automation for software solutions.
This article shows how to create a web application, add conditional formatting on cells with a few simplest lines of code using the Aspose.Cells API.
Using Aspose.Cells to Apply Conditional Formatting Based on Cell Value
- Download and Install Aspose.Cells.
- Download Aspose.Cells for JavaScript via C++.
- Install it on your development computer. All Aspose components, when installed, work in evaluation mode. The evaluation mode has no time limit and it only injects watermarks into produced documents.
- Create a project. Start your JavaScript project by initializing it. This example demonstrates usage in a browser-based web application.
- Add references.
Add a reference to Aspose.Cells to your project, for example by including the library as follows:
Apply Conditional Formatting Based on Cell Value
<script src="aspose.cells.js.min.js"></script>
<script type="text/javascript">
const { Workbook, SaveFormat, FormatConditionType, OperatorType, CellArea, Color } = AsposeCells;
AsposeCells.onReady({
license: "/lic/aspose.cells.enc",
fontPath: "/fonts/",
fontList: [
"arial.ttf",
"NotoSansSC-Regular.ttf"
]
}).then(() => {
console.log("Aspose.Cells initialized");
});
document.getElementById('runExample').addEventListener('click', async () => {
const fileInput = document.getElementById('fileInput');
if (!fileInput.files.length) {
document.getElementById('result').innerHTML = '<p style="color: red;">Please select an Excel file.</p>';
return;
}
const file = fileInput.files[0];
const arrayBuffer = await file.arrayBuffer();
// Instantiate workbook from uploaded file
const workbook = new Workbook(new Uint8Array(arrayBuffer));
// Access first worksheet
const worksheet = workbook.worksheets.get(0);
// Add conditional formatting collection
const cfCollection = worksheet.conditionalFormattings;
const idx = cfCollection.add();
const formatConditionCollection = cfCollection.get(idx);
// Define the cell area to apply conditional formatting (A1)
const area = CellArea.createCellArea(0, 0, 0, 0); // fromRow, fromCol, toRow, toCol
formatConditionCollection.addArea(area);
// Add a condition: Cell Value > 100
const conditionIndex = formatConditionCollection.addCondition(
FormatConditionType.CellValue,
OperatorType.Greater,
"100",
null
);
const formatCondition = formatConditionCollection.get(conditionIndex);
// Modify the style for the condition: bold and red font
const style = formatCondition.style;
if (!style.font) {
style.font = {};
}
style.font.bold = true;
style.font.color = Color.fromArgb(255, 255, 0, 0); // ARGB red
// Assign modified style back (property assignment pattern)
formatCondition.style = style;
// Save the modified workbook and provide download link
const outputData = workbook.save(SaveFormat.Xlsx);
const blob = new Blob([outputData]);
const downloadLink = document.getElementById('downloadLink');
downloadLink.href = URL.createObjectURL(blob);
downloadLink.download = 'conditional_formatting_result.xlsx';
downloadLink.style.display = 'block';
downloadLink.textContent = 'Download Modified Excel File';
document.getElementById('result').innerHTML = '<p style="color: green;">Conditional formatting applied to cell A1 (value > 100). Click the download link to get the modified file.</p>';
});
</script>
```
When the above code is executed, conditional formatting is applied to cell “A1” in the first worksheet of the output file (output.xls). The conditional formatting applied to A1 depends on the cell value. If the cell value of A1 is between 50 and 100 the background color is red due to the conditional formatting applied.
Using Aspose.Cells to Apply Conditional Formatting Based on Formula
- Applying conditional formatting depending on formula (Code Snippet) Below is the code to accomplish the task. It applies conditional formatting on B3.