C# SqlBulkCopy未从Excel导入数据

C# SqlBulkCopy未从Excel导入数据,c#,sql,excel,C#,Sql,Excel,我正在使用Visual Studio 12和C执行一个简单的项目,将数据从Excel导出到SQL Server。我成功地将Excel导入到数据集,但没有将它们插入到数据库中,尽管代码显示了一个积极的消息框,我已设置该消息框来告诉我何时可以 这意味着我的数据已成功导出到SQL,但当我选择“显示表数据”时,不会显示任何数据;桌子是空的。这是我的代码: using System; using System.Collections.Generic; using System.ComponentModel

我正在使用Visual Studio 12和C执行一个简单的项目,将数据从Excel导出到SQL Server。我成功地将Excel导入到数据集,但没有将它们插入到数据库中,尽管代码显示了一个积极的消息框,我已设置该消息框来告诉我何时可以

这意味着我的数据已成功导出到SQL,但当我选择“显示表数据”时,不会显示任何数据;桌子是空的。这是我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.IO;
using System.Data.OleDb;
using System.Data.Common;
using System.Data.SqlClient;

namespace testoledb    
{
   public partial class Form1 : Form
   {
      DataSet OleDs = new DataSet();
      OleDbDataAdapter OleAdapter = new OleDbDataAdapter();

      public Form1()
      {
         InitializeComponent();
      }

      private void Form1_Load(object sender, EventArgs e)
      {    
      }

      private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
      {
      }

      private void upload_excl_Click(object sender, EventArgs e)
      {
         string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
         path = Path.Combine(path, "AGENDA.xlsx");
         string path2 = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
         path2 = Path.Combine(path2, "Database1.mdf");

         string OleConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+path+@";Extended Properties='Excel 12.0 Macro;MDR=Yes;ImportMixedTypes=Text;TypeGuessRows=0'"; //,HDR=Yes;IMEX=1""";

         OleDbConnection OleConn = new OleDbConnection(OleConnectionString);    
         string OleStrCmd = "select * from [Feuil1$A1:I330]";    
         OleDbCommand OleCmd = new OleDbCommand(OleStrCmd, OleConn);

         try
         {
            OleConn.Open();
            OleDs.Clear();
            OleAdapter.SelectCommand = OleCmd;
            OleAdapter.Fill(OleDs);
            dataGridView1.DataSource = OleDs.Tables[0];

            //***************************************charger la base*******************************************************************************
            using (DbDataReader dr = OleCmd.ExecuteReader())
            {
               // SQL Server Connection String
               string sqlConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + path2 + ";Integrated Security=True";

               // Bulk Copy to SQL Server
               using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
               {
                  bulkCopy.DestinationTableName = "[dbo].[Table]";
                  bulkCopy.WriteToServer(dr);
                  MessageBox.Show("Data Exoprted To Sql Server Succefully");
               }
            }
                //***********************************************************************************************

         }
         catch (Exception ex)
         {
            MessageBox.Show(ex.ToString());    
         }
         finally
         {
            OleConn.Close();
         }
      }
   }
}

要确定是否真的要导入数据,可以执行以下操作:

OleDBCommand commandRowCount = new SqlCommand(
            "SELECT COUNT(*) FROM " +
            "dbo.Table;",
            OleConn);
long countStart = System.Convert.ToInt32(
            commandRowCount.ExecuteScalar());
这将为您提供开始时的行数,可能是0。然后,在导入数据后,这将:

// Perform a final count on the destination  
// table to see how many rows were added. 
long countEnd = System.Convert.ToInt32(
            commandRowCount.ExecuteScalar());
这将为您提供行的结尾。然后,通过计算countEnd-countStart可以知道导入了多少行。检查OleDs.Tables[0].Rows.Count的值也可能有帮助,以确保数据集中有行

有关SqlBulkCopy.WriteToServer的详细信息:

编辑:

我回顾了您的原始代码,看起来您不需要使用DbDataReader。由于已将数据加载到数据集中,因此有一个版本的SqlBulkCopy.WriteToServer将DataTable作为参数,因此您可以尝试以下操作:

       // SQL Server Connection String
       string sqlConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + path2 + ";Integrated Security=True";

       // Bulk Copy to SQL Server
       using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
       {
          bulkCopy.DestinationTableName = "[dbo].[Table]";
          bulkCopy.WriteToServer(OleDs.Tables[0]);
          MessageBox.Show("Data Exoprted To Sql Server Succefully");
       }

注意,我没有在DbDataReader中包含外部using块。尝试一下,看看这是否适合您。

您必须以这种方式导入数据吗?如果不是,您应该能够使用BULK Insert非常轻松地完成这项工作,并且您的表真的被称为Table吗?这可能是一个愚蠢的问题,但是您确定没有导入数据吗?如中所示,您已签入SSMS,但它不是?我之所以这么问,是因为听起来您已经编写了一个检索表记录的UI,我想确保没有出现错误的风险。顺便说一句,我也希望看到关于这个问题的更好的标题。如果你有答案的话,你会更容易得到答案。@dub stylee:不,我是一个初学者,我就是这样发现的,所以我试过了,如果还有其他答案,请带我去一个好的参考。谢谢你^^。你好,dub stylee请注意,我已经告诉过您,数据库表中没有任何引用:这表示我的数据已成功导出到SQL,但当我选择“显示表数据”时,没有显示任何数据;桌子是空的。这是我的代码:我的数据集上有行,但表中没有。。。请帮忙,没有例外显示我做错了什么,你能发布你的表格的定义吗?这可能是因为这些列可能与电子表格中的源列不匹配。它们是复制/过去的名称:是否有其他方法使其发生不使用批量方法请帮助me@user3820191,检查我的编辑,我希望添加了一种更简单的方法来编写数据,请告诉我是否有效。