Skale
asked on
Proper way to check worksheet is exist in workbook
I'm writing below codes to create and save workbook and checking sheet is existing in workbook. I didn't test it yet, before that i'd like to ask you what's proper way to declare them. Especially for sheet check and creating new workbook.
public static bool CreateWorkbook(string filename)
{
try
{
using (ClosedXML.Excel.XLWorkbook workbook = new ClosedXML.Excel.XLWorkbook())
{
ClosedXML.Excel.IXLWorksheet worksheet = workbook.Worksheets.Add(sheetName: "Default");
SaveAs(workbook, filename);
}
return true;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public static bool SaveAs(ClosedXML.Excel.XLWorkbook workbook, string filename)
{
try
{
workbook.SaveAs(filename);
return true;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public static bool IsSheetExists(ClosedXML.Excel.XLWorkbook workbook, string sheetname)
{
try
{
bool result = false;
foreach (ClosedXML.Excel.IXLWorksheet worksheet in workbook.Worksheets)
{
if (worksheet.Name == sheetname)
{
result = true;
break;
}
}
return result;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
Hi! Looks ok to me.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Maybe using:
return workbook.Worksheets.Contai ns(sheetna me);
return workbook.Worksheets.Contai