2015-12-22 75 views
0

我想將一個Excel文檔加載到我的VB.NET項目中,然後將所有數據從Excel文檔加載到我的SQL Server數據庫中。VB.NET通過代碼將Excel文檔加載到SQL Server數據庫表中

在SQL Server TCustomers表名和它有以下欄目:

CustomerID, FirstName, LastName, OrderID 

這是我的數據看起來如何在DataGridView:

CustomerID FirstName LastName OrderID 
01   Jack  Collin  100 

我的Excel表格中已列明的數據以同樣的方式。

Cell: A1 ---- B1 ---- C1 ---- D1 
CustomerID----FirstName-LastName-OrderID 
-02 ---- Mike ---- Angel ---- 200 

我曾嘗試使用下面的代碼來完成這個任務嘗試,但它不會做任何事情:

Dim ExcelConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Spreadsheet.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=Yes""") 
    ExcelConnection.Open() 

    Dim expr As String = "SELECT * FROM [Sheet1$]" 

    Dim objCmdSelect As OleDbCommand = New OleDbCommand(expr, ExcelConnection) 
    Dim objDataR As OleDbDataReader 

    Dim SQLconne As New SqlConnection() 
    Dim ConnString As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\MyDatabase.mdf;Integrated Security=True" 
    SQLconne.ConnectionString = ConnString 
    SQLconne.Open() 

    Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(SQLconne) 
     bulkCopy.DestinationTableName = "TCustomers" 

     Try 
      objDataR = objCmdSelect.ExecuteReader 
      bulkCopy.WriteToServer(objDataR) 
      objDataR.Close() 
      SQLconne.Close() 

     Catch ex As Exception 
      MsgBox(ex.ToString) 
     End Try 
    End Using 

任何幫助表示讚賞。

回答

相關問題