C# Logo

C# Create Style SpreadsheetGear API Sample

Excel-Compatible Samples for .NET

Description

An Excel Style provides a quick and easy way to apply, by name, a pre-defined set of cell formatting options to a range of cells. Formatting options include interior color, borders, font and number formats, lock cells, text orientation and others.

Styles in SpreadsheetGear are represented by the SpreadsheetGear.IStyle interface, which includes properties such as IStyle.Interior, IStyle.Borders, IStyle.Font, etc., to define the various formatting options of that style.

Built-In Styles

Microsoft Excel provides almost 50 built-in Styles, which are available in a dropdown from their Ribbon > Home Tab > Styles > Cell Styles. This includes named styles such as Normal (this is the default Style used for all cells in all worksheets of a workbook), Bad, Good, Neutral, Calculation, Note and many others. Built-in Styles can be modified from their default formatting options.

SpreadsheetGear supports these same built-in Styles and makes them accessible in a given workbook from the IWorkbook.Styles[...] collection. Assign a cell or range of cells a given Style by setting the IRange.Style property to the desired IStyle in the IWorkbook.Styles[...] collection. Example:

    worksheet.Cells["A1:D10"].Style = workbook.Styles["Good"];

Create A Custom Style

Create your own new Style by calling IWorkbook.Styles.Add(string name), which will return your named IStyle object that you can further customize as desired. The below sample code demonstrates creating an Inverted Style and applies it to the range A6:A10.

Sample C# Source Code

// Create a new workbook.
SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook();
SpreadsheetGear.IWorksheet worksheet = workbook.Worksheets["Sheet1"];
SpreadsheetGear.IRange cells = worksheet.Cells;

// Create a new Style and call it "My Style".
SpreadsheetGear.IStyle style = workbook.Styles.Add("Inverted");
style.Font.Color = SpreadsheetGear.Colors.White;
style.Interior.Color = SpreadsheetGear.Colors.Black;

// Add some cell data to A1:A10.
cells["A1:A10"].Value = "Hello World!";

// Apply custom style to A6:A10
cells["A6:A10"].Style = style;

worksheet.UsedRange.EntireColumn.AutoFit();