Prevent reading last Blank row from Excel file in ASP.Net C#

Last Reply 4 months ago By dharmendr

Posted 4 months ago

https://ibb.co/cLNx3S   ------------import barter syatem aspx

https://ibb.co/dea0OS   ------excel format

  i am importing the excel file into the database.Kindly check the excel file format. As you can see there are 4 entries. What is happening is that reader is reading the 4 entries from the file and after reading the 4th entry(4th row), it again goes into the while loop.

After reading the 4th entry, it should delete the file. Kindly check my code for upload.

here my problem is reader. It goes into the while loop for the fifth time which is not correct

while (dr.Read())
{
    ex_id = dr[0].ToString();
    string ex_uid = dr[1].ToString();
    //get second row data and assign it ex_name variable
    string ex_date = dr[2].ToString();
    //get thirdt row data and assign it ex_name variable
 
    string ex_dir = dr[3].ToString();
    dr.Close();          
    my_con.Close();

    if (System.IO.File.Exists(Excel_path))
    {
        System.IO.File.Delete(Excel_path);
    }
}
Posted 4 months ago

This is due to a blank row in your Excel. So before proceeding with code first you need to check the ex_id for null or empty. If not null or empty then proceed with your code.

while (dr.Read())
{
    if(!string.IsNullOrEmpty(dr[0].ToString()))
    {
        // Your code.
    }
}