Search code examples
c#exceldatatablecount

Count rows and columns that contains data from DataTable in C#.net


I've imported an excel file in my dataTable. For some reason I need to count my total rows and columns number. In my excel file, I've just used 3 rows giving 1,2,3 in 3 cells of Column A and Row 20,21,22.

Now the rows from 1 to 19 is not used, neither below 22, similarly, I didn't use Column B to the end of a typical excel file, just used A.

Thus, the correct answer would be Rows.Count = 3 and Columns.Count = 1.

Now, I want to count my used rows and columns of that DataTable. Please tell me how can I do that.


Solution

  • There is not going to be a flag to tell you "is this row used flag " what you will need to do is determine what value will be in the rows that will not be used in this case 1-19, 22 you need to deside if checking one column in a row is sufficent or if you need to check all rows in the column to see if the row is used. Say I know that if MemberShipNumber is equal to null or "" then I know the whole row is not going to be used this is how I would do my check:

      foreach(DataRow dr in table)
      {
    
         if (string.String.IsNullOrEmpty(dr["MembershipNumber"]))
         {
             Console.Write("This row is empty");
         } 
         else
         {
             Console.Write("This row is not empty there is more processing to do.");
         }
      }
    

    Hope that helps