C# Logo

C# Modify 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.

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"];

Modify A Style

Built-in Styles can be modified from their default formatting options. This sample will modify the Normal style to have a Yellow interior and use the Times New Roman font. Because "Normal" is the default Style for all cells in a workbook, this change will modify the entire workbook to use this style.

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;

// Get the "Normal" style for this workbook and modify it.
SpreadsheetGear.IStyle style = workbook.Styles["Normal"];
style.Font.Name = "Times New Roman";
style.Interior.Color = SpreadsheetGear.Colors.Yellow;

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