We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Cells.ApplyStyle Exception

Hi

I am trying to set the background color of some worksheets. This works fine for the first sheet but attempts to repeat the logic for an additional sheet results in "System.NullReferenceException' occurred in Aspose.Cells.dll"

Here is some simplified code:

Workbook wb_test = new Workbook();

Worksheet ws1 = wb_test.Worksheets.Add("test 1");
Style style1 = new Style();
style1.Pattern = BackgroundType.Solid;
style1.ForegroundColor = Color.White;
ws1.Cells.ApplyStyle(style1, new StyleFlag() { All = true });

Worksheet ws2 = wb_test.Worksheets.Add("test 2");
Style style2 = new Style();
style2.Pattern = BackgroundType.Solid;
style2.ForegroundColor = Color.White;
ws2.Cells.ApplyStyle(style2, new StyleFlag() { All = true });

The last row above results in the exception. If I call just the first block of code or just the second block of code there is no exception - the issue only occurs when the second Cells.ApplyStyle is called.

Any ideas what the issue is?

Thanks

Hi Brendan,

Thanks for your posting and using Aspose.Cells.

Please use Workbook.CreateStyle() method to create a new style object and it will fix your code. Please see the following code and it works fine. Changes are highlighted in red color.

C#


Workbook wb_test = new Workbook();


Worksheet ws1 = wb_test.Worksheets.Add(“test 1”);

Style style1 = wb_test.CreateStyle();

style1.Pattern = BackgroundType.Solid;

style1.ForegroundColor = Color.White;

ws1.Cells.ApplyStyle(style1, new StyleFlag() { All = true });


Worksheet ws2 = wb_test.Worksheets.Add(“test 2”);

Style style2 = wb_test.CreateStyle();

style2.Pattern = BackgroundType.Solid;

style2.ForegroundColor = Color.White;

ws2.Cells.ApplyStyle(style2, new StyleFlag() { All = true });

Hi

That worked thanks. Should Workbook.CreateStyle() always be used when a style is required or is "new Style()" appropriate in some situations?

Hi Brendan,

Thanks for your posting and using Aspose.Cells.

Please always use Workbook.CreateStyle() because it does some necessary initialization of the style object which is not performed when Style is directly created.