I have an Excel file(.xlsx) and I am trying to upload the content of the file into a Sql server table. Iam using the SQL bulk copy to bulk insert the data. The data gets inserted into the table but I find that the data is not inserted properly.
Here is the sample Excel data-
This is the code for Sql bulk copy:
string fname = Path.GetFileName(fup_addRoute.FileName);
fup_addRoute.SaveAs(Server.MapPath("/Admin/UserRoutes/" + fname));
string path = Server.MapPath("/Admin/UserRoutes/" + fname);
using (OleDbConnection connection = new OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path)))
{
OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
connection.Open();
System.Data.Common.DbDataReader dr = command.ExecuteReader();
SqlBulkCopy bulkInsert = new SqlBulkCopy(con);
bulkInsert.DestinationTableName = "routesdata";
bulkInsert.WriteToServer(dr);
connection.Close();
dr.Close();
bulkInsert.Close();
}
Data after insert:
Only last row gets inserted and the first column value in excel sheet is missing. The xid column in table is an auto-increment column.
This procedure was easy in MySql with 'load data infile' but I just migrated to Sql server. What am I doing wrong in my code. Suggestions please.