This project has moved and is read-only. For the latest updates, please go here.

How to Verify if a Worksheet already exists?

Jan 10, 2011 at 2:30 AM

Currently I'm using the following validation:

if (updatePopulationPackage.Workbook.Worksheets.Count != 9)
                {
                    ExcelWorksheet saveSheet = updatePopulationPackage.Workbook.Worksheets.Add("Export Certification Report");
}

else
                {
                    //Use existing file and update its list
                    ExcelWorksheet saveSheet = updatePopulationPackage.Workbook.Worksheets["Export Certification Report"];

I'd like to replace my if condition from the current .Count-dependent code to something like:

 

updatePopulationPackage.Workbook.Worksheets["the worksheet name is here"].Exists == false

 

However this does not work. I've ran a search and found the following:

// get worksheet
var sheet = package.Workbook.Worksheets["Sheet1"];

I tried implementing this such that:

var sheet = package.Workbook.Worksheets["Sheet1"];
if (sheet.ToString != <condition here>)
{
//insert code here to create new worksheet
}
else
{
//insert code here to update existing worksheet
}

But run-time fails. Is there any way I could check if a specific worksheet already exists in the file? Thanks!

Jan 10, 2011 at 6:30 PM

Try this...

var sheet=package.Workbook.Worksheets["Sheet1"];
if(sheet==null)
{
  //Add a new sheet...
  sheet=package.Workbook.Worksheets.Add("Sheet1");
}

Jan

Jan 11, 2011 at 6:38 PM

using package.Workbook.WorkSheets["nameofthesheet"] is giving me an argument null exception

 

What can be the reason for it?

Description says:

 'package.Workbook.Worksheets' threw an exception of type 'System.ArgumentNullException' OfficeOpenXml.ExcelWorksheet {System.ArgumentNullException}

Let me know how to fix this?

 

Thanks

Srikanth Kambhampati

Jan 11, 2011 at 9:28 PM

I'm not sure what you are doing, but If the worksheet don't exist the indexer will return null.

Jan 11, 2011 at 10:49 PM
jankallman wrote:

Try this...

var sheet=package.Workbook.Worksheets["Sheet1"];
if(sheet==null)
{
  //Add a new sheet...
  sheet=package.Workbook.Worksheets.Add("Sheet1");
}

Jan

 Thanks Jan, verified working and pretty helpful. Cheers!

Jan 14, 2011 at 12:50 AM

Jan

The problem was I tried to open a sheet that was sent by email directly, then it would give me this error.

 

I tried opening and saving it and then executing the program and that worked. Not sure what the problem was.

 

Thanks

Srikanth Kambhampati