1

I'm trying to use EPPlus to loop through an Excel workbook's sheets, but I'm not having any luck figuring out the syntax.

I'm using C# right now. I was able to get it working in VB.NET, but not C#.

This is what I have that is not working in C#:

object Workbook01 = new OfficeOpenXml.ExcelPackage(WorkbookFilePath).Workbook;

foreach (object sheet01 in Workbook01.Worksheets){

    // Code here.

}

This gives an error that says:

'object' does not contain a definition for 'Worksheets' and no extension method 'Worksheets' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

This is what I have in VB.NET that works fine:

Dim Wkbk As Object
Wkbk = New OfficeOpenXml.ExcelPackage(wkbkFilePath).Workbook

For Each sheet01 In Wkbk.Worksheets

    ' Code here

Next sheet01

Maybe it's a mistake to compare C# to VB.NET for this project, but, either way, I need to figure out how to loop through all sheets with EPPlus in C#.

user247702
  • 23,641
  • 15
  • 110
  • 157
  • 2
    What is the type of `ExcelPackage(WorkbookFilePath).Workbook`? Change `object` to that type. – Arian Motamedi Feb 15 '16 at 18:56
  • Possible duplicate of [Trying to read an Excel file with EPPlus works on the server, but not through a browser](http://stackoverflow.com/questions/22717271/trying-to-read-an-excel-file-with-epplus-works-on-the-server-but-not-through-a) – MethodMan Feb 15 '16 at 18:59
  • @MethodMan not at all a duplicate. – user247702 Feb 15 '16 at 19:00

2 Answers2

3

Workbook01 is an object here, so you only have access to the members of System.Object:

object Workbook01 = new OfficeOpenXml.ExcelPackage(WorkbookFilePath).Workbook;

If you don't want to write out the type name, use var:

var Workbook01 = new OfficeOpenXml.ExcelPackage(WorkbookFilePath).Workbook;

You should do the same in your loop:

foreach (var sheet01 in Workbook01.Worksheets){

See Difference between "var" and "object" in C# for an explanation on the difference.

Community
  • 1
  • 1
user247702
  • 23,641
  • 15
  • 110
  • 157
0

C# is a lot stricter with respect to types than VB.NET is (without Option Strict).

You need to declare a variable of type Workbook instead of object:

OpenOfficeXml.Workbook Workbook01 = new ...

VB.NET does some magic so that you can use the properties and methods of Workbook on an object variable. C# expects you to specify the correct type to avoid misunderstandings. You can also use the var keyword to let the compiler determine the right type of a variable.

Markus
  • 20,838
  • 4
  • 31
  • 55