To answer why the exception uses the First() method - I would bet the money that your sheet3 in excel is empty. Remember that a Cells object contains only links to a cell with actual content. But if all the cells in excel are empty, then the Cells collection in EPPlus.
For example, this works great when creating a new sheet:
using (var package = new ExcelPackage(fi)) { var brandNewSheet = package.Workbook.Worksheets.Add("BrandNewSheet"); brandNewSheet.Cells["A1"].LoadFromCollection(new[] {"A", "B", "C", "D", "E"}); brandNewSheet.Cells["B1"].LoadFromCollection(new[] {"A", "B", "C", "D", "E"}); brandNewSheet.Cells["A1:B5"].Merge = true; var mergedId = brandNewSheet.MergedCells[1, 1]; brandNewSheet.Cells[mergedId].First().Value = "123"; package.Save(); }
But if you comment out the calls to LoadFromCollection , you get an exception at runtime:
using (var package = new ExcelPackage(fi)) { var brandNewSheet = package.Workbook.Worksheets.Add("BrandNewSheet"); //brandNewSheet.Cells["A1"].LoadFromCollection(new[] {"A", "B", "C", "D", "E"}); //brandNewSheet.Cells["B1"].LoadFromCollection(new[] {"A", "B", "C", "D", "E"}); brandNewSheet.Cells["A1:B5"].Merge = true; var mergedId = brandNewSheet.MergedCells[1, 1]; brandNewSheet.Cells[mergedId].First().Value = "123"; //Cells is empty so: System.InvalidOperationException: Sequence contains no elements package.Save(); }
As others explain, there is no need to call First() to get what you want, but you believe that I at least addressed it.
Ernie source share