Search code examples
c#visual-studioepplus

Visual Studio 2015 breaks EPPlus Colors


Spent hours fussing with this until I narrowed it down to VS 2015. This worked just fine in VS 2013:

myWorksheet.Cells[1, 1].Style.Fill.BackgroundColor.SetColor(Color.LightGray);

But in VS 2015, though it compiles just fine, when I run the solution it throws an exception:

Color.LightGray = {System.NullReferenceException: Object reference not set to an instance of an object
at Microsoft.Win32.SystemEvents.AddEventHandler(Object key, Delegate value
at Microsoft.Win32.SystemEvents.add_UserPreferenceChanging(UserPreferenceChangingEventH...

Is there another way to specify color that will work?


Solution

  • The issue isn't with VS 2015. If I do this:

    using (var excel = new ExcelPackage())
    {
        var ws = excel.Workbook.Worksheets.Add("sheet1");
        ws.Cells[1, 2].Value = "light grey";
        ws.Cells[1, 2].Style.Fill.PatternType = ExcelFillStyle.Solid;
        ws.Cells[1, 2].Style.Fill.BackgroundColor.SetColor(Color.LightGray);
    
        excel.SaveAs(new System.IO.FileInfo(@"C:\temp\temp.xlsx"));
    }
    

    then I get the expected output:

    enter image description here

    A couple of possible reasons this could throw an exception:

    • Have you first set the Fill's .PatternType property to ExcelFillStyle.Solid ?
    • Do you have a reference to System.Drawing for the correct target framework? (That this happened after a VS upgrade makes me wonder if your references are targetting .NET 4.5 but your project targetting a later version?).