Link to home
Start Free TrialLog in
Avatar of Skale
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;
            }

        }

Open in new window



     
  public static bool SaveAs(ClosedXML.Excel.XLWorkbook workbook, string filename)
        {
            try
            {
                workbook.SaveAs(filename);
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

Open in new window


  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;
            }
        }

Open in new window

Avatar of Eduard Ghergu
Eduard Ghergu
Flag of Romania image

Hi! Looks ok to me.
ASKER CERTIFIED SOLUTION
Avatar of Eduard Ghergu
Eduard Ghergu
Flag of Romania image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Maybe using:

return workbook.Worksheets.Contains(sheetname);