简体   繁体   中英

SqlBulkCopy not importing data from Excel

I'm doing a simple project exporting data from Excel to SQL Server with Visual Studio 12 and C#. I managed to import from Excel to a DataSet, but not insert them into my database, although the code is showing a positive message box that I've set to tell me when it is OK.

It's saying that my data was successfully exported to SQL, but when I choose "show table data" no data is shown; the table is empty. This is my code:

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

To tell if you are really importing the data, you could do something like this:

OleDBCommand commandRowCount = new SqlCommand(
            "SELECT COUNT(*) FROM " +
            "dbo.Table;",
            OleConn);
long countStart = System.Convert.ToInt32(
            commandRowCount.ExecuteScalar());

That will give you the # of rows to begin with, probably 0. Then AFTER importing the data, this:

// Perform a final count on the destination  
// table to see how many rows were added. 
long countEnd = System.Convert.ToInt32(
            commandRowCount.ExecuteScalar());

That will give you the ending # of rows. Then you can tell how many rows were imported by calculating countEnd - countStart . It might also be helpful to check the value of OleDs.Tables[0].Rows.Count as well, to make sure there are rows in your DataSet .

More information about SqlBulkCopy.WriteToServer : http://msdn.microsoft.com/en-us/library/434atets(v=vs.110).aspx

EDIT:

I am looking back over your original code, and it looks like you do not need to use the DbDataReader . Since you already have the data loaded into your DataSet , there is a version of SqlBulkCopy.WriteToServer that takes a DataTable as the argument, so you could try this:

       // 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");
       }

Notice, I did not include the outer using block with the DbDataReader . Give that a try and see if that works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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