C# SqlBulkCopy插入null而不是Double

C# SqlBulkCopy插入null而不是Double,c#,asp.net,sql-server,excel,sqlbulkcopy,C#,Asp.net,Sql Server,Excel,Sqlbulkcopy,我正在尝试将excel文件导入我的网站,然后将其内容保存在sql server中 我的sqlbulkcopy问题是,当它填充数据库时,某些列填充了错误的空值!而该列有一个非空的双精度值 代码如下: void ImporttoDatatable() { try { if (FileUpload3.HasFile) { string FileName = FileUpload3.FileName;

我正在尝试将excel文件导入我的网站,然后将其内容保存在sql server中 我的sqlbulkcopy问题是,当它填充数据库时,某些列填充了错误的空值!而该列有一个非空的双精度值

代码如下:

            void ImporttoDatatable()
{

    try
    {
        if (FileUpload3.HasFile)
        {
            string FileName = FileUpload3.FileName;
            string path = Path.Combine(Server.MapPath("~/ImportDocument"), Guid.NewGuid().ToString() + Path.GetExtension(FileUpload3.PostedFile.FileName));


            FileUpload3.PostedFile.SaveAs(path);




            using (OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + "; Extended Properties = \"Excel 8.0;HDR=Yes;IMEX=2\" "))
            {


                conn.Open();
                OleDbcon.Open();
                OleDbCommand command = new OleDbCommand("Select [IdOftable], [Time],[InstrumentLeftHand],[LeftSwitch],[LeftKnob],[ForceFeedbackLeftHand],[CumTimeLeftForceOverThreshold],[CumTimeLeftForceOver2xThreshold],[TranslationLeft_x],[TranslationLeft_y],[TranslationLeft_z],[quatLeft_x],[quatLeft_y],[quatLeft_z],[quatLeft_w],[InstrumentRightHand],[RightSwitch],[RightKnob],[ForceFeedbackRightHand],[CumTimeRightForceOverThreshold],[CumTimeRightForceOver2xThreshold],[TranslationRight_x],[TranslationRight_y],[TranslationRight_z],[quatRight_x],[quatRight_y],[quatRight_z],[quatRight_w],[BloodEmittedFrame],[BloodCurrentFrame],[TotalBloodEmitted],[TotalWhiteFibreCut],[TotalRedFibreCut],[Volume0_Brain],[Volume1_Tumor],[Volume2_Tumor] from [Sheet1$]", OleDbcon);

                //OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(command);
                 DbDataReader dr = command.ExecuteReader();
                using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn))
                {
                bulkCopy.DestinationTableName =  "MyExcel";
                    try
                    {
                        bulkCopy.BulkCopyTimeout = 400;
                        bulkCopy.WriteToServer(dr);
                        bulkCopy.BatchSize = 16000;
                    }
                    catch (Exception ex)
                    {
                        Response.Write(ex.ToString());
                    }
                    finally
                    {
                        dr.Close();
                    }
                    OleDbcon.Close();
                    bulkCopy.Close();

                }
            }
        } lblmessage.Text = "The File Succssesfully Imported ";
    }
    catch (Exception ex)
    {
        Response.Write(ex.ToString());
    }
}
这是sql表定义:

        CREATE TABLE [dbo].[MyExcel] (
[IdOftable]                        NVARCHAR (50) NOT NULL,
[Time]                             FLOAT (53)    NULL,
[InstrumentLeftHand]               NVARCHAR (50) NULL,
[LeftSwitch]                       FLOAT (53)    NULL,
[LeftKnob]                         FLOAT (53)    NULL,
[ForceFeedbackLeftHand]            FLOAT (53)    NULL,
[CumTimeLeftForceOverThreshold]    FLOAT (53)    NULL,
[CumTimeLeftForceOver2xThreshold]  FLOAT (53)    NULL,
[TranslationLeft_x]                FLOAT (53)    NULL,
[TranslationLeft_y]                FLOAT (53)    NULL,
[TranslationLeft_z]                FLOAT (53)    NULL,
[quatLeft_x]                       FLOAT (53)    NULL,
[quatLeft_y]                       FLOAT (53)    NULL,
[quatLeft_z]                       FLOAT (53)    NULL,
[quatLeft_w]                       FLOAT (53)    NULL,
[InstrumentRightHand]              NVARCHAR (50) NULL,
[RightSwitch]                      FLOAT (53)    NULL,
[RightKnob]                        FLOAT (53)    NULL,
[ForceFeedbackRightHand]           FLOAT (53)    NULL,
[CumTimeRightForceOverThreshold]   FLOAT (53)    NULL,
[CumTimeRightForceOver2xThreshold] FLOAT (53)    NULL,
[TranslationRight_x]               FLOAT (53)    NULL,
[TranslationRight_y]               FLOAT (53)    NULL,
[TranslationRight_z]               FLOAT (53)    NULL,
[quatRight_x]                      FLOAT (53)    NULL,
[quatRight_y]                      FLOAT (53)    NULL,
[quatRight_z]                      FLOAT (53)    NULL,
[quatRight_w]                      FLOAT (53)    NULL,
[BloodEmittedFrame]                NVARCHAR (50) NULL,
[BloodCurrentFrame]                FLOAT (53)    NULL,
[TotalBloodEmitted]                FLOAT (53)    NULL,
[TotalWhiteFibreCut]               FLOAT (53)    NULL,
[TotalRedFibreCut]                 FLOAT (53)    NULL,
[Volume0_Brain]                    FLOAT (53)    NULL,
[Volume1_Tumor]                    FLOAT (53)    NULL,
[Volume2_Tumor ]                   FLOAT (53)    NULL,
PRIMARY KEY CLUSTERED ([IdOftable] ASC)
 );
当我运行代码时没有异常,但是当我检查服务器内部的数据时,它有一些值的空值,这些值不应该为空=(

我使用visual studio express 2012 for web。如何更正它


谢谢大家

谢谢大家的帮助 最后,当我使用@GarethD所说的内容时,它对我起作用

如果有人需要,我将发布编辑后的代码:

 string name = (string)(Session["LoginUserName"]);
   if(FileUpload3.FileName == null ){

   lblmessage.Text = "Choose the file First then click import ";
   string display = "             Choose the file First then click import                   ";
   ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + display + "');", true);
   }
   else 
   {


       string path = Path.Combine(Server.MapPath("~/ImportDocument"), Guid.NewGuid().ToString() + name + Path.GetExtension(FileUpload3.PostedFile.FileName));


   FileUpload3.PostedFile.SaveAs(path);
   OleDbConnection dbConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + "; Extended Properties = \"Excel 8.0;HDR=Yes;IMEX=2\" ");
    dbConnection.Open();
    try
   {       

       // Get the name of the first worksheet:
       DataTable dbSchema = dbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
       if (dbSchema == null || dbSchema.Rows.Count < 1)
       {
           throw new Exception("Error: Could not determine the name of the first worksheet.");
       }
       string firstSheetName = dbSchema.Rows[0]["TABLE_NAME"].ToString();

       // Now we have the table name; proceed as before:
       OleDbCommand dbCommand = new OleDbCommand("Select [IdOftable], [Time],[InstrumentLeftHand],[LeftSwitch],[LeftKnob],[ForceFeedbackLeftHand],[CumTimeLeftForceOverThreshold],[CumTimeLeftForceOver2xThreshold],[TranslationLeft_x],[TranslationLeft_y],[TranslationLeft_z],[quatLeft_x],[quatLeft_y],[quatLeft_z],[quatLeft_w],[InstrumentRightHand],[RightSwitch],[RightKnob],[ForceFeedbackRightHand],[CumTimeRightForceOverThreshold],[CumTimeRightForceOver2xThreshold],[TranslationRight_x],[TranslationRight_y],[TranslationRight_z],[quatRight_x],[quatRight_y],[quatRight_z],[quatRight_w],[BloodEmittedFrame],[BloodCurrentFrame],[TotalBloodEmitted],[TotalWhiteFibreCut],[TotalRedFibreCut],[Volume0_Brain],[Volume1_Tumor],[Volume2_Tumor] from [" + firstSheetName + "]", dbConnection);
       OleDbDataReader dbReader = dbCommand.ExecuteReader();

       using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn))
       {

           bulkCopy.DestinationTableName = "MyExcel";
           try
           {
               conn.Open();
               bulkCopy.BulkCopyTimeout = 400;
               bulkCopy.WriteToServer(dbReader);
               bulkCopy.BatchSize = 16000;
               conn.Close();

           }

           catch (Exception ex)
           {
               Response.Write(ex.ToString());
           }
           finally
           {
               bulkCopy.Close();
               dbReader.Close();
               //lblmessage.Text = " data successfully imported  ";
           //    Response.Write(@"<script language=""javascript"">alert('Details saved successfully')</script>");
               string display = "             Data Duccessfully Imported  Now Click On Calculate the result to calculate your results taking in your account The calculation will take a while , please wait   ";
               ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + display + "');", true);
           }



       }
   }
   finally
   {
       dbConnection.Close();
   }
}
string name=(string)(会话[“LoginUserName]”);
if(FileUpload3.FileName==null){
lblmessage.Text=“首先选择文件,然后单击导入”;
string display=“先选择文件,然后单击导入”;
RegisterStartupScript(this.GetType(),“myalert”,“alert(“+”显示+“);”,true);
}
其他的
{
string path=path.Combine(Server.MapPath(“~/ImportDocument”)、Guid.NewGuid().ToString()+name+path.GetExtension(FileUpload3.PostedFile.FileName));
FileUpload3.PostedFile.SaveAs(路径);
OleDbConnection dbConnection=new-OleDbConnection(“Provider=Microsoft.ACE.OLEDB.12.0;Data Source=“+path+”;Extended Properties=\”Excel 8.0;HDR=Yes;IMEX=2\”);
dbConnection.Open();
尝试
{       
//获取第一个工作表的名称:
DataTable dbSchema=dbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,null);
if(dbSchema==null | | dbSchema.Rows.Count<1)
{
抛出新异常(“错误:无法确定第一个工作表的名称。”);
}
string firstSheetName=dbSchema.Rows[0][“TABLE_NAME”].ToString();
//现在我们有了表名;请按照前面的步骤继续:
OleDbCommand dbCommand=新的OleDbCommand(“选择[IdOftable]、[Time]、[InstrumentLeftHand]、[LeftSwitch]、[LeftKnow]、[ForceFeedbackLeftHand]、[CumTimeLeftForceOver2xThreshold]、[CumTimeLeftForceOver2xThreshold]、[TranslationLeftuX]、[TranslationLeftuY]、[TranslationLeftuZ]、[QuatLeftuX]、[QuatLeftuX]、[QuatLefty\QuatLeftuY]、[QuatLeftuZ]、[QuatLe,[RightSwitch]、[RightKnob]、[ForceFeedbackRightHand]、[CumtimeRightForceOver Threshold]、[CumtimeRightForceOver 2xThreshold]、[TranslationRight_x]、[TranslationRight_x]、[TranslationRight_z]、[Quattright_x]、[Quattright_y]、[Quattright_z]、[BloodEmittedFrame]、[BloodCurrentFrame]、[TotalBloodEmissed]、[TotalWhiteFibreCut]、[Total,[Volume0_Brain]、[Volume1_Tumor]、[Volume2_Tumor]来自[“+firstSheetName+”],数据库连接);
OleDbDataReader dbReader=dbCommand.ExecuteReader();
使用(SqlBulkCopy bulkCopy=newsqlbulkcopy(conn))
{
bulkCopy.DestinationTableName=“MyExcel”;
尝试
{
conn.Open();
bulkCopy.BulkCopyTimeout=400;
bulkCopy.WriteToServer(dbReader);
bulkCopy.BatchSize=16000;
康涅狄格州关闭();
}
捕获(例外情况除外)
{
Response.Write(例如ToString());
}
最后
{
bulkCopy.Close();
dbReader.Close();
//lblmessage.Text=“数据导入成功”;
//响应。写入(@“警报('成功保存详细信息”);
string display=“数据已成功导入现在单击“计算结果”以计算您的结果考虑到您的帐户计算将需要一段时间,请稍候”;
RegisterStartupScript(this.GetType(),“myalert”,“alert(“+”显示+“);”,true);
}
}
}
最后
{
dbConnection.Close();
}
}

但除一个字段外,所有字段都可以为空…我还没有检查
SqlBulkCopy.WriteToServer(IDataReader)的内部工作方式
,但我的猜测是,由于从电子表格中读取不会产生强类型读取器,因此有一个相当松散的转换器,在转换失败时使用
DbNull
。我昨天遇到了这个问题,发现在添加额外代码以显式迭代读取器和填充强类型
Da时花费了大量时间taTable
使用显式转换,然后将此表写入服务器要比尝试反映.NET以找出发生这种情况的确切原因快得多。@e4rthdog感谢您的回复,但当我将其更改为NOTNULL时,异常“system.INVALIDUctionException列'column name'不允许dbnull.value”将出现,这意味着相同的问题会出现,无论是否为null=(@GarethD感谢您的回复,我尝试了带有DataAdapter的DataTable“忽略它将花费的时间”它出现了DBNull异常,这就是为什么我更改为bulk,但仍然是同一个问题!我建议您根据此显式添加
ColumnMappings
。我发现这有助于解决歧义,并确保数据正确映射到表