2016-12-04 201 views
-3

我想使用一种方法,我脱离了CodePlex,它从Excel导出数据到SQL表中。我做了一些小的代码调整,但我似乎仍然无法获取要导入的数据。有人看到我的语法有什么明显的错误吗?谢谢。C#导入Excel数据到SQL表

static void Main(string[] args) 
     { 
      importdatafromexcel("C:/Users/usname/Desktop/TestDirectories/FileSystemWatcher/Test_123.xlsx"); 
     } 

public static void importdatafromexcel(string excelfilepath) 
     { 
      //declare variables - edit these based on your particular situation 
      string ssqltable = "Name"; 
      // make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have different 

      string myexceldataquery = "select Name,EmployeeID from [sheet1$]"; 
      try 
      { 
       //create our connection strings 
       string sexcelconnectionstring = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + excelfilepath + ";Extended Properties=" + "\"excel 8.0;hdr=yes;\""; 

       //MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelfilepath + ";Extended Properties=Excel 8.0;HDR=YES'"); 

       string ssqlconnectionstring = "server=DESKTOP-6CIMC97;Initial Catalog=TestDB;integrated security=true;connection reset = false"; 

       //<add name="ProductContext" connectionString="Server=DESKTOP-6CIMC97; Initial Catalog=ProductApps; Integrated Security=True" providerName="System.Data.SqlClient" /> 

       //execute a query to erase any previous data from our destination table 
       string sclearsql = "delete from " + ssqltable; 
       SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring); 
       SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn); 
       sqlcmd.Connection.Open(); 
       sqlcmd.ExecuteNonQuery(); 
       sqlconn.Close(); 

       //series of commands to bulk copy data from the excel file into our sql table 
       OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring); 
       OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn); 
       oledbconn.Open(); 
       OleDbDataReader dr = oledbcmd.ExecuteReader(); 
       SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring); 
       bulkcopy.DestinationTableName = ssqltable; 
       bulkcopy.WriteToServer(dr); 
       //while (dr.Read()) 
       //{ 
        // bulkcopy.WriteToServer(dr); 
       //} 

       oledbconn.Close(); 
      } 
      catch (Exception ex) 
      { 
       //handle exception 
      } 
     } 
+0

您必须更具体地了解您实际获得的行为。您是否尝试过使用调试器来完成此操作? –

+0

我已经尝试过,但对编程来说是新的,而且对于断点来说并不是最好的。我在Excel中添加了一个连接,并在Main中添加了一个实际的方法,但在断开后我没有看到任何错误。当我运行代码时,控制台应用程序打开并在大约一秒后关闭,就好像它已经成功了一样,但是当我检查表时没有数据存在。 – AndrewC10

+0

这看起来像是一次学习调试的机会:-)尝试创建自己的阅读器循环,以查看是否可以从源表中实际读取数据。手动将随机数据放在名称表中,看它是否至少被删除。只需验证整个过程的每一步。 –

回答

1

的问题是在这里:如果你是遍历结果一个接一个

while (dr.Read()) 
{ 
    bulkcopy.WriteToServer(dr); 
} 

while (dr.Read())块是有用的。

但是,你不是在迭代结果。您希望批量复制操作进行迭代。

只需使用

bulkcopy.WriteToServer(dr); 
+0

感谢您的回复。我注释了我的while语句,并将bulkcopy命令提升了,如上面的代码所示。它似乎仍然不想导入。我很担心它在某个连接字符串中的内容。 db名称是TestDB,表格是Name。再次感谢您的帮助。 – AndrewC10

0

这取代它应该为你工作。

private void SaveFileToDatabase(string filePath) 
{ 
    String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True"; 

    String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath); 
    //Create Connection to Excel work book 
    using (OleDbConnection excelConnection = new OleDbConnection(excelConnString)) 
    { 
     //Create OleDbCommand to fetch data from Excel 
     using (OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection)) 
     { 
      excelConnection.Open(); 
      using (OleDbDataReader dReader = cmd.ExecuteReader()) 
      { 
       using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection)) 
       { 
        //Give your Destination table name 
        sqlBulk.DestinationTableName = "Excel_table"; 
        sqlBulk.WriteToServer(dReader); 
       } 
      } 
     } 
    } 
} 


private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl) 
{ 


    string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName); 

    fileUploadControl.SaveAs(filePath); 

    return filePath; 

} 

欲了解更多信息,请参阅下面的链接。

https://www.codeproject.com/tips/636719/import-ms-excel-data-to-sql-server-table-using-csh

http://www.c-sharpcorner.com/UploadFile/0c1bb2/inserting-excel-file-records-into-sql-server-database-using/

正如你所知道的,有很多方法可以做到你想做的事情。