I was working with sheets in excel and I have to create and delete several of these. The problem is that, doing it as I do, I have a rather " dirty " code in my opinion and I was wondering if there is any way to make it cleaner.
//Añadimos una hoja auxiliar que guardamos en una variable auxiliar
Worksheet aux = null;
try
{
//Añado la hoja
aux = workbook.Worksheets.Add("DATOS AUX");//Si existe lanza argumentException
}
catch (ArgumentException)
{
aux = workbook.Worksheets["DATOS AUX"];//Igualo Aux a la hoja que se llame "DATOS AUX"
aux.Clear(); //La vacío por si contiene algún tipo de
}
try
{
workbook.Worksheets.Add("Hoja1");//Añado hoja si existe lanza ARgumentException
}
catch (ArgumentException)
{
var hoja1= workbook.Worksheets["Hoja1"];//Igualo hoja1 a la hoja
hoja1.Clear(); //la vacío
}
I use ArgumentException
it because it is the exception that it gives me when the sheet that I try to create already exists and in the library that I use I do not see any method to do something likeif(Workbook.worksheet[indice].exists)...
You can use LINQ to check if a sheet exists. To do this you must do a previous step, a cast of the collection
Worksheets
to the typeExcel.Worksheet
, and later you can check if the name exists:If what you want is to return the sheet if it exists, or null otherwise, you can use
FirstOrDefault
:If the sheet exists, it returns it to you
hoja
, otherwise ithoja
will benull
.Edit
If you are not allowed to use Linq (there are some very weird people), you can create a simple method: