Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c# - SQLBulkCopy inserts a new row with NULL values for all columns

I have this code which works fine and loads the excel data into an SQL table. The only problem is that it also inserts a new row with NULL values for all columns.

using (OleDbConnection excel_con = new OleDbConnection(conString))
{
excel_con.Open();
string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
DataTable dtExcelData = new DataTable();
 using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + Path.GetFileName(excelPath) + "]", excel_con))
            {
                oda.Fill(dtExcelData);
            }
            excel_con.Close();

using (SqlConnection con = new SqlConnection(consString))
            {
                using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
                {
                    //Set the database table name
                    sqlBulkCopy.DestinationTableName = "dbo.mySQLTable";


                    sqlBulkCopy.BulkCopyTimeout = 200;

                    sqlBulkCopy.ColumnMappings.Add("Employee", "Employee_Name");
                    sqlBulkCopy.ColumnMappings.Add("Sal/Hourly", "Sal/Hourly");

                    sqlBulkCopy.ColumnMappings.Add("Total", "Total"); 

                    con.Open();
                    sqlBulkCopy.WriteToServer(dtExcelData);
                    con.Close();
                }
            }
}

This 2988 row is not present in excel, but the code creates it. Any help is appreciated.

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could change your query to skip empty rows in excel:

"SELECT * FROM [" + Path.GetFileName(excelPath) + "] WHERE [Employee] IS NOT NULL"

This should avoid that empty rows are added to the DataTable. Of course you could also remove them later but it would be less efficient. For example:

dtExcelData = dtExcelData.AsEnumerable()
    .Where(r => !String.IsNullOrEmpty(r.Field<string>("Employee")))
    .CopyToDataTable();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...