Reputation: 4457
I have excel sheet with 4 columns and 4 rows. When I read the columns and rows Count
with Microsoft.Office.Interop.Excel.WorkSheet
the count of rows and columns are 1048576 for rows and for columns 16384. The count must be 4 for rows and 4 for columns. What did I miss ?
ApplicationClass excelApp = null;
Workbook myWorkBook = null;
Worksheet mySheet = null;
Range dataRange = null;
excelApp = new ApplicationClass();
myWorkBook = excelApp.Workbooks.Open(@"C:\Users\Dev2Admin\Desktop\Employees.xlsx");
mySheet = (Worksheet)myWorkBook.Sheets["Sheet1"];
for (int row = 1; row < mySheet.Rows.Count; row++) // Count is 1048576 instead of 4
{
for (int col = 1; col < mySheet.Columns.Count; col++) // Count is 16384 instead of 4
{
dataRange = (Range)mySheet.Cells[row, col];
Console.Write(String.Format(dataRange.Value2.ToString() + " "));
}
Console.WriteLine();
}
Upvotes: 9
Views: 12995
Reputation: 79
There is also one more thing, that rows and colums start with 1 not 0 so you need to set the for loops range to <= to get all data, not just <
Upvotes: 0
Reputation: 8104
You have omitted UsedRange
property, the correct used column or row count on your sheet you get like this:
int totalColumns = mySheet.UsedRange.Columns.Count;
int totalRows = mySheet.UsedRange.Rows.Count;
Upvotes: 7