Foreach loop to go through worksheets

Hi,

I am trying to loop through the workbook and have written the following code below where I pass a book and sheetname into a method and then for each sheet within the book I check to see if the name exists. The error I am getting is under the foreach loop

Error 2872 foreach statement cannot operate on variables of type 'Aspose.Cells.Workbook' because 'Aspose.Cells.Workbook' does not contain a public definition for 'GetEnumerator'

I am using vs 2005 and coding in C# using 4.4.0.0 aspose.cells.dll version. thanks.

private static bool WorksheetExistsByName(Workbook book, String sheetName)

{

foreach(Worksheet sheet in book)

{

if (sheet.Name.Equals(sheetName, StringComparison.InvariantCultureIgnoreCase))

return true;

}

return false;

}

Hi,

Thank you for considering Aspose.

Well, you have to use book.WorkSheets collection in the foreach loop. Please Modify your code as following,

private static bool WorksheetExistsByName(Workbook book, String sheetName)

{

foreach(Worksheet sheet in book.Worksheets)

{

if (sheet.Name.Equals(sheetName, StringComparison.InvariantCultureIgnoreCase))

return true;

}

return false;

}

Thank You & Best Regards,

Hi,

Well, i think you are making a minor mistake in your code, kindly change your code to:

private static bool WorksheetExistsByName(Workbook book, String sheetName)

{

foreach(Worksheet sheet in book.Worksheets)

{

if (sheet.Name.Equals(sheetName, StringComparison.InvariantCultureIgnoreCase))

return true;

}

return false;

}

Thank you.

That workout great, thanks guys.

Hi,

Can you please let me know how to iterate worksheets of an workbook in APPOSE.CELLS for java.

thanks

Hi,

Thanks for your posting and considering Aspose.Cells for Java.

Please see the following sample code, it loads the source Excel file and iterate all worksheets in a for loop and print their names.

I have attached the source Excel file used in this code and also shown the Console Output produced by the code for your reference.

Java


String filePath = “D:\Downloads\Sample.xlsx”;


//Create workbook instance from excel file

Workbook workbook = new Workbook(filePath);


//Iterate all worksheets inside the workbook and print their names

for(int i=0; i<workbook.getWorksheets().getCount(); i++)

{

//Access the i th worksheet

Worksheet worksheet = workbook.getWorksheets().get(i);


//Print worksheet name

System.out.println(worksheet.getName());

}

Console Output:
MySheet1
MySheet2
MySheet3
MySheet4
MySheet5