繁体   English   中英

SqlBulkCopy不从Excel导入数据

[英]SqlBulkCopy not importing data from Excel

我正在做一个简单的项目,使用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的值也可能会有所帮助,以确保DataSet有行。

有关SqlBulkCopy.WriteToServer详细信息: http : //msdn.microsoft.com/zh-cn/library/434atets( SqlBulkCopy.WriteToServer .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");
       }

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM