Home » excel » c# – Loading Excel data into SQL server – Extra NULL Rows added

c# – Loading Excel data into SQL server – Extra NULL Rows added

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m trying to import data from an Excel sheet into a sqlserver database. I used the sample code that is in this link. However, when an import is made extra 22 rows with NULL values are being copied. I’m not sure how to remove the NULL values.

Database screen shot

How to&Answers:

In the select statement, try adding a WHERE clause to exclude the nulls.
EX.

select student,rollno,course from [sheet1$]

Becomes:

select student,rollno,course from [sheet1$] where student IS NOT NULL

Answer:

In the code

    while (dr.read())
    {
        bulkcopy.writetoserver(dr);
    }

you could check dr to see whether all of the columns are null, and if so skip the call to bulkcopy.writetoserver().