How to count rows or columns with data in a worksheet in Infragistics.Excel? For example, myWorkbook.Worksheets[0].Rows.Count
jonesmar said:int numColumns = sheet.Columns[((ICollection<WorksheetColumn>)sheet.Columns).Count - 1].Index + 1;int numRows = sheet.Rows[((ICollection<WorksheetRow>)sheet.Rows).Count - 1].Index + 1; foreach(WorksheetRow row in sheet.Rows) { foreach(WorksheetCell cell in row.Cells) { int rowNo = row.Index; int colNo = col.Index; object value = cell.Value; // Process cell... }}
I don't see why you would need to get the full number of rows or columns in this code example (maybe you are using those numbers elsewhere though), but getting the count in this was may also be inaccurate, especially if some rows or columns are skipped in the worksheet. Try this instead:
int numRows = 0;Dictionary<int,object> validColumns = new Dictionary<int,object>();
foreach(WorksheetRow row in sheet.Rows) { bool rowHasData = false;
foreach(WorksheetCell cell in row.Cells) { int colNo = cell.ColumnIndex; object value = cell.Value;
if(value != null) { rowHasData = true;
// Add an entry to the dictionary if the column had no cells before // or overwrite the entry for the column if it already has cells validColumns[colNo] = null; }
// Process cell... }
if(rowHasData) numRows++;}
int numColumns = validColumns.Count;
However, this will ignore rows and cells with no data that have formatting. If you would like to get the count that included those rows and cell as well, you would need to modify this slightly.
And my maths its 8M cells...! :-)
Sorry for the formatting...
Martin
I'm really keen to not have to create 16 million WorksheetCell objects, and iterate over 16 million cells in order to get the few cells that have values... But fortunately there is a solution.
Cheers,
After loading the rows and columns collection will have entries for all rows and columns that has data. However we can just look at the index property to determine the row and column positions. To get the number of rows and columns look at the index of the last entry.
And in my example I have omitted the check whether the Rows and Columns collections are in fact empty...
}
Fair enough, it worked for my small test 2x2 spreadsheet - guess I was just lucky...