C# Logo

C# Rich-Text Formatting (RTF) Font SpreadsheetGear API Sample

Excel-Compatible Samples for .NET

Description

Use the SpreadsheetGear.IRange.GetCharacters(int start, int length) method to access a sub-portion of a cell's text, also known as Rich-Text Formatting (RTF). This method returns a SpreadsheetGear.ICharacters object, which provides a number of font formatting methods and properties including an ICharacters.Font property which you would use to apply the desired font formatting, such as IFont.Name, IFont.Size, IFont.Bold, IFont.Italic, IFont.Underline, IFont.Superscript, IFont.Subscript, IFont.Color, IFont.ThemeColor and others. The GetCharacters(...) method's start argument is 0-based.

Rich text can also be used with TextFrame-based shapes such as a TextBox or Cell Comment.

This sample demonstrates formatting sub-portions of the text "SpreadsheetGear Engine for .NET" in cell A1 in a variety of ways using the SpreadsheetGear.ICharacters object returned from the SpreadsheetGear.IRange.GetCharacters(int start, int length) method.

Sample C# Source Code

// Create a new workbook and some local variables.
SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook();
SpreadsheetGear.IWorksheet worksheet = workbook.ActiveWorksheet;
SpreadsheetGear.IRange cells = worksheet.Cells;

// Get a reference to cell A1.
SpreadsheetGear.IRange cell = cells["A1"];

// Add text to the cell.
cell.Value = "SpreadsheetGear Engine for .NET";

// Set font size for entire text to 24 points.
cell.Font.Size = 24;

// Set "Spreadsheet" text to dark blue.
SpreadsheetGear.ICharacters spreadsheetChars = cell.GetCharacters(0, 11);
spreadsheetChars.Font.Color = SpreadsheetGear.Color.FromArgb(255, 0, 0, 128);

// Set "Gear" text to a shade of red.
SpreadsheetGear.ICharacters gearChars = cell.GetCharacters(11, 4);
gearChars.Font.Color = SpreadsheetGear.Color.FromArgb(255, 233, 14, 14);

// Set "Engine" text style.
SpreadsheetGear.ICharacters engineChars = cell.GetCharacters(16, 6);
engineChars.Font.Bold = true;

// Set "for" text style.
SpreadsheetGear.ICharacters forChars = cell.GetCharacters(23, 3);
forChars.Font.Underline = SpreadsheetGear.UnderlineStyle.Single;

// Set ".NET Standard" text style.
SpreadsheetGear.ICharacters netStandardChars = cell.GetCharacters(27, 4);
netStandardChars.Font.Italic = true;

// AutoFit the column.
cell.EntireColumn.AutoFit();