Search code examples
c#excelinfragistics

Check if worksheet exist using infragistics


i need to check if a worksheet exist in excel and if not, to create it. I'm using infragistics and the following code gives me the following error:

use of unassigned local variable 'workSheet'.

this is the code:

Workbook workbook = new Workbook();
 Worksheet workSheet;
 foreach (Something result in results)
  {            
     foreach (Something item in result.Something)
     {
         if (!workbook.Worksheets.Exists(item.GetType().Name))
         {
             workSheet = workbook.Worksheets.Add(item.GetType().Name);
         }
         // cell font
        IWorkbookFont oFont = workSheet.Workbook.CreateNewWorkbookFont();
....
    }
}

The error is about the: IWorkbookFont oFont = workSheet.Workbook.CreateNewWorkbookFont()

on the workSheet variable.

thanks.


Solution

  • Here is how you can avoid the error. Initialize worksheet to null when you declare it. Do not forget the null check before accessing the worksheet.

    Workbook workbook = new Workbook();
    Worksheet workSheet = null;
    foreach (Something result in results)
    {            
         foreach (Something item in result.Something)
         {
             if (!workbook.Worksheets.Exists(item.GetType().Name))
             {
                 workSheet = workbook.Worksheets.Add(item.GetType().Name);
             }
    
             if (workSheet != null)
             {
    
                 // cell font
                 IWorkbookFont oFont = workSheet.Workbook.CreateNewWorkbookFont();
                 ....
             }
            ....
         }
    }