JDo
JDo

Reputation: 358

Cell styles in SpreadsheetGear C# .NET

I try create excel document via SpreadsheetGear. And i would like to apply some styles on headers?fonts etc same as on screenshot:

enter image description here

I wrote the following code:

 static string[] fieldsName =
    {
        "Name",
        "LastName",
        "Address",
        "Phone"

    };       
private static void Main(string[] args)
 {
        var workbook = Factory.GetWorkbook();
        IWorksheet worksheet = workbook.ActiveWorksheet;
        IRange cells = worksheet.UsedRange;
        cells["A1:C1"].Style.Font.Bold = true;
        cells["A1:C1"].Font.Color = Color.FromArgb(255, 255, 255);
        cells["A1:C1"].Interior.Color = Color.FromArgb(0, 204, 0);

        cells["A1"].Value = " ";
        cells["B1"].Value = "My demo excel file";
        cells["C1"].Value = " ";

        cells["A2:C2"].Style.Font.Bold = true;
        cells["A2"].Value = "Field";
        cells["B2"].Value = "Description";
        cells["C2"].Value = "Value";
       
        FillDecisionCells(cells);
        
        workbook.SaveAs(@"D:\test.xlsx", FileFormat.OpenXMLWorkbook);
 } 

Then I try to fill Field column without bold font style:

private static void FillDecisionCells(IRange cells)
    {
        for (var i = 2; i < fieldsName.Length; i++)
        {
            cells[i, 0].Value = fieldsName[i];
        }
    }

But end up with all the text in bold:

enter image description here

Upvotes: 1

Views: 1051

Answers (1)

Tim Andersen
Tim Andersen

Reputation: 3184

See https://stackoverflow.com/a/28533330/233365 for an explanation for this. But bottom-line, you need to set the cell’s font directly such as…

cells["A2:C2"].Font.Bold = true;  // Good

…and not the cell’s style’s font:

cells["A2:C2"].Style.Font.Bold = true;  // Bad

Setting the cell’s style will affect all other cells using that same style, which in the case of the “Normal” style (probably the style being set in your case) is usually most if not all other cells. Hence bold everywhere.

Upvotes: 3

Related Questions