How to: Format a Cell or Range of Cells

  • 4 minutes to read

Besides using styles that provide the capability to apply a predefined set of format attributes to multiple cells, you can also extend cell formatting with some explicit attributes. To perform direct cell formatting, use the CellRange object properties that are inherited from the Formatting interface (for example, Formatting.Fill, Formatting.Font, Formatting.Alignment and Formatting.Borders). Initially, these properties are set according to the style applied to the cell.

Thus, the actual cell appearance is determined by the format settings specified by the applied style and the cell's format settings. Each of these formatting types provides a set of flags (Formatting.Flags). Each flag corresponds to a specific group of format attributes. You can use these flags when formatting a cell, to control whether to use attributes specified in the applied style or attributes specified directly for the cell.

Group Attributes Flag
Alignment Horizontal and vertical alignment of cell content, indentation, text wrap, text rotation and text shrinking. StyleFlags.Alignment
Borders Cell border line styles and colors. StyleFlags.Borders
Fill Cell background color and shading type. StyleFlags.Fill
Font Cell font settings (name, style, color and size). StyleFlags.Font
Number Format Cell number format. StyleFlags.Number
Protection Cell protection options (Locked and Hidden). StyleFlags.Protection

This example demonstrates how to format cells in a worksheet.

// Access the cell to be formatted.
Cell cell = worksheet.Cells["B2"];

// Specify font settings (font name, color, size and style).
cell.Font.Name = "MV Boli";
cell.Font.Color = Color.Blue;
cell.Font.Size = 14;
cell.Font.FontStyle = SpreadsheetFontStyle.Bold;

// Specify cell background color.
cell.Fill.BackgroundColor = Color.LightSkyBlue;

// Specify text alignment in the cell. 
cell.Alignment.Vertical = SpreadsheetVerticalAlignment.Center;
cell.Alignment.Horizontal = SpreadsheetHorizontalAlignment.Center;
// Access the range of cells to be formatted.
CellRange range = worksheet.Range["C3:E6"];

// Begin updating of the range formatting. 
Formatting rangeFormatting = range.BeginUpdateFormatting();

// Specify font settings (font name, color, size and style).
rangeFormatting.Font.Name = "MV Boli";
rangeFormatting.Font.Color = Color.Blue;
rangeFormatting.Font.Size = 14;
rangeFormatting.Font.FontStyle = SpreadsheetFontStyle.Bold;

// Specify cell background color.
rangeFormatting.Fill.BackgroundColor = Color.LightSkyBlue;

// Specify text alignment in cells.
rangeFormatting.Alignment.Vertical = SpreadsheetVerticalAlignment.Center;
rangeFormatting.Alignment.Horizontal = SpreadsheetHorizontalAlignment.Center;

// End updating of the range formatting.

The image below shows formatted cells (the workbook is opened in Microsoft® Excel®).


See Also