Click here to Skip to main content
15,888,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to get the row count from a data table without empty rows while reading from excel in asp.net with c#?

I am reading the data from excel sheet using OledbConnection. But empty rows also are coming in data table. I want to avoid the same.

My code to read data from excel is as below:

C#
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.DataSet ds;
System.Data.OleDb.OleDbDataAdapter MyCommand;
MyConnection = new System.Data.OleDb.OleDbConnection(connStr);
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
ds = new System.Data.DataSet();
MyCommand.Fill(dt);
MyConnection.Close();



ds.Tables.Add(dt);
oItem = dt.Rows.Count;


What I have tried:

My code to read data from excel is as below:

C#
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.DataSet ds;
System.Data.OleDb.OleDbDataAdapter MyCommand;
MyConnection = new System.Data.OleDb.OleDbConnection(connStr);
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
ds = new System.Data.DataSet();
MyCommand.Fill(dt);
MyConnection.Close();



ds.Tables.Add(dt);
oItem = dt.Rows.Count;
Posted
Updated 6-Jul-16 20:38pm

refer this

C#
DataTable dt = new DataTable();
        dt.Columns.Add("ID");
        dt.Columns.Add("Name");
        dt.Columns.Add("Address");
        dt.Rows.Add(null, null, DBNull.Value);
        dt.Rows.Add(1, 2, "a");
        dt.Rows.Add(12, 23, "b");

        object[] possibleNullOrEqualentValues = {null,"",DBNull.Value};

        DataTable dtTemp = dt;
        for (int i = 0; i < dtTemp.Rows.Count; i++)
        {
            DataRow currentRow = dtTemp.Rows[i];
            DataRow targetRow = dt.Rows[i];
           bool isEmptyRow =  currentRow.ItemArray.All(k => possibleNullOrEqualentValues.Contains(k));
           if (isEmptyRow)
               targetRow.Delete(); 
        }

        dt.AcceptChanges();
        int RowCount = dt.Rows.Count;
 
Share this answer
 
First clone your datatable and delete empty rows, then after you can count rows
see below snippet
C#
DataTable dt1= dt.Clone();
for (int i = dt1.Rows.Count - 1; i >= 0; i--)
{
    if (dt1.Rows[i]["col1"] == DBNull.Value && dt1.Rows[i]["col2"] == DBNull.Value)
     {
        dt1.Rows[i].Delete();
     }
}
dt1.AcceptChanges();
int RowCount = dt1.Rows.Count;
 
Share this answer
 
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900