SqlBulkCopy不从Excel导入数据

时间:2014-07-24 23:27:20

标签: c# sql excel

我正在做一个简单的项目,使用Visual Studio 12和C#将数据从Excel导出到SQL Server。我设法从Excel导入到DataSet,但没有将它们插入到我的数据库中,尽管代码显示了一个正面的消息框,我已设置它告诉我何时可以。

它说我的数据已成功导出到SQL,但当我选择“show table data”时,没有显示数据;桌子是空的。这是我的代码:

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();
         }
      }
   }
}

1 个答案:

答案 0 :(得分:0)

要判断您是否真的在导入数据,可以执行以下操作:

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的值也可能会有所帮助,以确保DataSet中有行。

有关SqlBulkCopy.WriteToServer的更多信息:http://msdn.microsoft.com/en-us/library/434atets(v=vs.110).aspx

修改

我正在回顾您的原始代码,看起来您不需要使用DbDataReader。由于您已将数据加载到DataSet,因此有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");
       }

注意,我没有将using块包含在DbDataReader中。尝试一下,看看它是否适合你。