How to count empty rows when reading from Excel

醉酒当歌 提交于 2019-12-01 18:18:41

I think your problem is with your connection string. I tested the below code and it worked for me:

     DataSet Contents = new DataSet();
     using (OleDbDataAdapter adapter = new OleDbDataAdapter("select FirstName,LastName,Email,Mobile from [" + mySheet + "]", connection))
     {
         adapter.Fill(Contents,"MyTable");
     }

     foreach (DataRow content in Contents.Tables["MyTable"].Rows)
     {
         if (content[0].ToString() == "" && content[0].ToString() == "" && content[0].ToString() == "" && content[0].ToString() == "")
         {
             Console.WriteLine("Empty Row");
         }
         else
         {
             Console.WriteLine(content[0] + " | " + content[1] + " | " + content[2] + " | " + content[3]);
         }
     }

My Connection String is:

    string cnnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"C:\\Untitled 1.xls\";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
neha kochhar

check below code :It will return the empty rows..

System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source = " + strFileName + "; Extended Properties = \"Excel 8.0;HDR=NO;IMEX=1\";"); /*for office 2007 connection*/
                    conn.Open();
string strQuery = "SELECT * FROM [" + Table + "]";
System.Data.OleDb.OleDbDataAdapter adapter = new  System.Data.OleDb.OleDbDataAdapter(strQuery, conn);
System.Data.DataTable ExcelToDataTable = new System.Data.DataTable();
adapter.Fill(ExcelToDataTable);

DT = ExcelToDataTable.Copy();

int count = DT.Rows.Cast<DataRow>().Where(row => row.ItemArray.All(field => field is System.DBNull || string.Compare((field as string).Trim(), string.Empty) == 0)).ToList().Count();

As stated by @Knvn

You need to specifiy the file extension .xls with the file name in your connection string.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!