Search code examples
sql-serverexcelcopybulkexceldatareader

Sqlbulkcopy gives error on float conversion (asp.net c#)


Iam trying to insert bulk of excel to sql

sqlBulk.WriteToServer(dReader); gives error

The given value of type String from the data source cannot be converted to type float of the specified target column.

Iam using below code

 System.Data.SqlClient.SqlConnection strConnection;
    strConnection = new System.Data.SqlClient.SqlConnection("Data Source=L06DPSGCD0001;Initial Catalog=ProductionEfficiency;User ID=sample;Password=sample");

    string path = ("C:\\Users\\s3802616\\Desktop\\" + (FileUpload1.FileName));

    System.Diagnostics.Debug.WriteLine("C:\\Users\\s3802616\\Desktop\\" + (FileUpload1.FileName));
    string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=" + "\"" + "Excel 12.0;HDR=YES;" + "\"";
    //Create Connection to Excel work book

    OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
    //Create OleDbCommand to fetch data from Excel

    OleDbCommand cmd = new OleDbCommand("Select [Model],[Process],[STD_Hours],[UOM],[Section] from [Sheet1$]", excelConnection);
    //OleDbCommand cmd = new OleDbCommand("Select * from [Sheet1$]", excelConnection);
    excelConnection.Open();
    strConnection.Open();
    OleDbDataReader dReader;
    dReader = cmd.ExecuteReader();
    SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
    //Give your Destination table name

    sqlBulk.DestinationTableName = "dbo.tblProcessStdHours";
    sqlBulk.WriteToServer(dReader);
    excelConnection.Close();
    strConnection.Close();
    lblStatus.Text = "Uploaded Successfully";

Pls Suggest.


Solution

  • Error says it all.

    You are trying to copy "string/chars" in target column which is of "float" type.

    You need to change data type of your target column in database table "dbo.tblProcessStdHours" to varchar.