How to open a worksheet in an Excel file using EPPlus

Sep 28, 2015 at 2:08 PM
There is a Default Excel Sheet. I want to Export data to the default Excel template which I can able to do using OledbCommand. I want some formatting to be done after exporting the data.

When I to try to open a worksheet in an Excel file, I am getting System.ArgumentException : An item with the same key has already been added.

Please find below the code I used for accessing the Excel file.

using (OfficeOpenXml.ExcelPackage xlPackage = new OfficeOpenXml.ExcelPackage(new FileInfo(FilePathAndName)))
            var worksheet = xlPackage.Workbook.Worksheets[3];

            if (worksheet != null)
                //if (Worksheets.Count > 0)
               // var worksheet = xlPackage.Workbook.Worksheets["Accounts"];

                using (OfficeOpenXml.ExcelRange range = worksheet.Cells["C8:H8"])
                    range.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    range.Style.Font.SetFromFont(new Font("Arial", 10));
                    range.Style.HorizontalAlignment = ExcelHorizontalAlignment.CenterContinuous;
                    worksheet.View.ShowGridLines = true;
                // }

Thanks Suresh