Format Cells and Cell Ranges
- 10 minutes to read
You can format individual cells and cell ranges to customize their appearance and control how cell content is displayed. The Spreadsheet Document API supports the following formatting options:
- Cell Formatting
- Use the Cell.Format property to access direct formatting settings. You can configure font, fill, borders, alignment, number format, and protection settings.
- Cell Styles
- Create styles and apply them to cells and cell ranges with the Cell.StyleName or CellRange.StyleName property.
- Workbook Themes
- Use a workbook theme to define theme fonts and colors that you can use in cell formatting and styles.
Formatting Priority
Formatting settings can come from different sources. The Spreadsheet Document API resolves these settings in the following order of priority:
Direct cell formatting
Settings specified through the
Cell.Formatproperty have the highest priority.Cell style
Settings specified in the style assigned through
Cell.StyleNameorCellRange.StyleNameapply when the corresponding setting is not specified by direct cell formatting.Workbook theme
Theme settings define the actual font or color when a cell or style uses a theme-based font or color.
Format Options
The CellFormat object contains the following options:
| Property | Description |
|---|---|
| Font | Specifies font settings. |
| Fill | Specifies the cell fill. |
| Borders | Specifies cell borders. |
| Alignment | Specifies cell content alignment. |
| NumberFormat | Specifies the format of cell values. |
| Protection | Specifies cell protection settings. |
Format a Cell
Use the Cell.Format property to apply formatting to an individual cell.
The following code snippet specifies the font and alignment for cell B2:
Cell cell = worksheet.Cells["B2"];
cell.Format.Font = new FontFormat(
"Arial",
12,
CellColor.Automatic,
bold: true,
italic: true,
strikeout: false,
UnderlineType.None);
cell.Format.Alignment = new AlignmentFormat(
SpreadsheetHorizontalAlignment.Center,
SpreadsheetVerticalAlignment.Center);
Format a Cell Range
Use CellRange methods to format all cells in a range. You can apply all formatting settings simultaneously, modify individual settings, clear settings, or retrieve formatting settings shared by all cells in the range.
Apply All Formatting Settings
Call the CellRange.ApplyFormat(format) method to apply a CellFormat object to every cell in a range. The method replaces all direct formatting settings of these cells.
The following code snippet applies a bold font and center alignment to cells A1:D1:
CellFormat format = new CellFormat() {
Font = new FontFormat("Arial", 12).WithBold(true),
Alignment = new AlignmentFormat(
SpreadsheetHorizontalAlignment.Center,
SpreadsheetVerticalAlignment.Center)
};
worksheet["A1:D1"].ApplyFormat(format);
Note
The CellRange.ApplyFormat method assigns the same CellFormat object to every cell in the range. If you modify this CellFormat object later (for example, through the Cell.Format property of one cell), the change affects all cells that share the object. ApplyFont, ApplyFill, ApplyBorders, ApplyAlignment, ApplyProtection, and ApplyNumberFormat methods of the CellRange class also modify the shared object. If you call one of these methods for part of the range, the change also applies to other cells that share the object. To format part of the range differently, call the CellFormat.Clone() method and pass the copy to the ApplyFormat method for this part before you modify formatting settings.
Modify Individual Formatting Settings
Call one of the following methods to modify a single formatting setting. Other formatting settings of each cell in the range remain unchanged.
- CellRange.ApplyFont(font)
- CellRange.ApplyFill(fill)
- CellRange.ApplyBorders(borders)
- CellRange.ApplyAlignment(alignment)
- CellRange.ApplyProtection(protection)
- CellRange.ApplyNumberFormat(numberFormat)
The following code snippet applies a number format and a solid fill to cells B2:D10 and keeps their font, borders, alignment, and protection settings:
CellRange range = worksheet["B2:D10"];
range.ApplyNumberFormat(new NumberFormat("#,##0.00"));
range.ApplyFill(new SolidFillFormat(CellColor.FromRgb(242, 242, 242)));
Note
A single call to the ApplyFormat method or a method that modifies an individual setting can format up to 1,048,576 cells. If the range contains more cells, the method throws an InvalidOperationException. Calls that clear formatting settings have no size limit.
Clear Formatting Settings
Pass null (Nothing in VB.NET) to a method that modifies an individual setting to clear this setting in all cells in the range. Pass null to the ApplyFormat method to clear all direct formatting settings.
The following code snippet clears the fill of cells B2:D10 and then clears all their direct formatting settings:
CellRange range = worksheet["B2:D10"];
// Clear the fill and keep other formatting settings.
range.ApplyFill(null);
// Clear all direct formatting settings.
range.ApplyFormat(null);
Get Common Formatting Settings
Call the CellRange.GetFormat() method to get formatting settings that all cells in the range have in common. If at least one formatting setting differs between cells, the method returns null. The method returns a CellFormat copy (changes to the returned object do not affect cells).
The following code snippet copies common cell formatting settings from A1:D1 to A2:D2:
CellFormat format = worksheet["A1:D1"].GetFormat();
if (format != null)
worksheet["A2:D2"].ApplyFormat(format);
Customize Font Settings
Use the CellFormat.Font property to specify font settings.
The FontFormat structure includes the following properties:
| Property | Description |
|---|---|
| Name | Specifies the font name. |
| Size | Specifies the font size. |
| Color | Specifies the font color. |
| Bold | Specifies whether the font is bold. |
| Italic | Specifies whether the font is italic. |
| Strikeout | Specifies whether the font is struck through. |
| Underline | Specifies the underline type. |
| Script | Specifies the text script type. |
| SchemeStyle | Specifies the font scheme style. |
Tip
Use the With... methods to modify font settings with a fluent syntax. You can chain multiple methods to configure the font.
The following code snippet configures font settings:
CellFormat cellFormat = new CellFormat();
cellFormat.Font = new FontFormat()
.WithName("Arial")
.WithBold(true)
.WithItalic(true)
.WithSize(12)
.WithColor(CellColor.Automatic)
.WithUnderline(UnderlineType.Double);
Cell cell = worksheet.Cells["A1"];
cell.Format = cellFormat;
Apply Rich Text Formatting to Cell Text
Rich text formatting applies different font settings to parts of the cell text. A RichText object contains text runs (RichTextRun objects). Each run contains a text fragment and font settings for the fragment.
To apply rich text formatting to cell text, follow the steps below:
Create a
RichTextobject.Call the RichText.AddRun(text, font) method to add a run with specified font settings. The
fontparameter is optional. If you omit it, the run uses the cell font.Pass the
RichTextobject to the Cell.SetRichText(value) method.
The following code snippet displays the Total: 1,250 USD text in cell A1. The number is bold and red, and the currency code is italic:
FontFormat boldFont = new FontFormat("Calibri", 11)
.WithBold(true)
.WithColor(CellColor.FromRgb(192, 0, 0));
FontFormat italicFont = new FontFormat("Calibri", 11)
.WithItalic(true);
RichText richText = new RichText()
.AddRun("Total: ")
.AddRun("1,250", boldFont)
.AddRun(" USD", italicFont);
Cell cell = worksheet.Cells["A1"];
cell.SetRichText(richText);
The Cell.Value property gets the text of all runs as a text value. If you assign a value to the Cell.Value property or a formula to the Cell.Formula property, the cell loses rich text formatting.
If the RichText object contains a single run without font settings, the SetRichText method assigns plain text to the cell. The RichText.IsPlainText property defines whether a RichText object contains plain text.
Read Rich Text from a Cell
Use the Cell.HasRichText property to check whether a cell contains rich text. Call the Cell.GetRichText() method to get the rich text. The GetRichText method returns null if the cell contains no rich text.
Use the RichText.Runs property to access text runs. RichTextRun.Text and RichTextRun.Font properties get the run text and font settings.
The following code snippet displays the text of each run in cell A1 and specifies if the text is bold:
Cell cell = worksheet.Cells["A1"];
if (cell.HasRichText) {
RichText richText = cell.GetRichText();
foreach (RichTextRun run in richText.Runs) {
bool isBold = run.Font.HasValue && run.Font.Value.Bold;
Console.WriteLine($"{run.Text} (bold: {isBold})");
}
}
Specify Cell Background
Use the CellFormat.Fill property to specify a cell background.
Solid Fill
Assign a SolidFillFormat object to apply a solid fill:
CellFormat cellFormat = new CellFormat();
cellFormat.Fill = new SolidFillFormat(
CellColor.FromColor(Color.LightBlue));
Cell cell = worksheet.Cells["A1"];
cell.Format = cellFormat;
Pattern Fill
Assign a PatternFillFormat object to apply a pattern fill:
CellFormat cellFormat = new CellFormat();
cellFormat.Fill = new PatternFillFormat(
PatternType.LightGray,
CellColor.FromColor(Color.LightBlue),
CellColor.FromColor(Color.White));
Cell cell = worksheet.Cells["A1"];
cell.Format = cellFormat;
Gradient Fill
Assign a GradientFillFormat object to apply a gradient fill:
GradientFillFormat gradientFill = new GradientFillFormat(GradientFillType.Linear, 0.9);
gradientFill.Stops.Add(
new GradientFillStop(0, CellColor.FromColor(Color.LightBlue)));
gradientFill.Stops.Add(
new GradientFillStop(100, CellColor.FromColor(Color.White)));
CellFormat cellFormat = new CellFormat();
cellFormat.Fill = gradientFill;
Cell cell = worksheet.Cells["A1"];
cell.Format = cellFormat;
Add Cell Borders
Use the CellFormat.Borders property to specify cell borders. A BorderFormat object defines left, top, right, and bottom borders.
The following code snippet adds a thin border to all sides of a cell:
CellFormat cellFormat = new CellFormat();
cellFormat.Borders = new BorderFormat(
new BorderLine(
BorderLineStyle.Thin,
CellColor.FromColor(Color.Gray)));
Cell cell = worksheet.Cells["A1"];
cell.Format = cellFormat;
Specify Colors
Use the CellColor class to specify an RGB color, a palette color, or a theme color. You can use CellColor to specify colors for fonts, fills, and borders.
cell.Format.Font = new FontFormat(
"Arial",
14,
CellColor.FromColor(Color.DarkBlue),
bold: true,
italic: true,
strikeout: false,
UnderlineType.None);
Align Cell Content
Use the CellFormat.Alignment property to specify how cell content is aligned.
The AlignmentFormat structure includes the following options:
| Property | Description |
|---|---|
| Horizontal | Specifies horizontal alignment. |
| Vertical | Specifies vertical alignment. |
| WrapText | Specifies whether to wrap text within a cell. |
| ShrinkToFit | Specifies whether to reduce the text size to fit the cell. |
| Indent | Specifies the indentation level. The value must be between 0 and 250. |
| RotationAngle | Specifies the text rotation angle. |
| VerticalText | Specifies whether to display text vertically. Setting this property resets RotationAngle to 0. |
The following code snippet centers cell content horizontally and vertically and enables text wrapping:
CellFormat cellFormat = new CellFormat();
cellFormat.Alignment = new AlignmentFormat(
SpreadsheetHorizontalAlignment.Center,
SpreadsheetVerticalAlignment.Center,
wrapText: true,
indent: 0,
rotationAngle: 0);
Cell cell = worksheet.Cells["A1"];
cell.Format = cellFormat;
Configure Cell Protection
Use the CellFormat.Protection property to specify cell protection settings. These settings correspond to options in the Format Cells → Protection dialog in Microsoft Excel.
The ProtectionFormat structure includes the following properties:
| Property | Description |
|---|---|
| Locked | Specifies whether the cell is locked. |
| Hidden | Specifies whether to hide the cell formula. |
The following code snippet locks a cell and hides its formula:
CellFormat cellFormat = new CellFormat();
cellFormat.Protection = new ProtectionFormat(
locked: true,
hidden: true);
Cell cell = worksheet.Cells["A1"];
cell.Format = cellFormat;
Tip
Locking cells and hiding formulas has no effect until you protect the worksheet.