2016-09-07 204 views
0

我搜索爲什麼從Excel到SQL表輸入不(通過vb.net)故障數據從Excel中複製使用BulkCopy到SQL(vb.net)

Excel文件中工作良好的原因輸入包含1300行和12列。最後五列包含價格。 輸入後,我的表格如果填滿了excel數據,除了兩個最後的「價格」列,其中所有的數據都是'空'。 奇怪的是,我的所有「價格」列在SQL目標表中的格式與相同的類型(十進制(18,2)),即使在Excel文件。 對於副本,我使用SqlBulkCopy,我想知道這個函數是不是有限的。

這裏是我的代碼:

 Dim ExcelConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & fTransp & ";Extended Properties=""Excel 12.0 Xml;HDR=Yes""") 

     ExcelConnection.Open() 

     Dim RequeteExcelTransp As String = "SELECT * FROM [ExcelCetup$]" 

     Dim objCmdSelect As OleDbCommand = New OleDbCommand(RequeteExcelTransp, ExcelConnection) 

     Dim objDR As OleDbDataReader 

     Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(ConnexionLinkyStat) 
      bulkCopy.DestinationTableName = "dbo." & TableTransp & "" 

      Try 
       objDR = objCmdSelect.ExecuteReader 
       bulkCopy.WriteToServer(objDR) 
       objDR.Close() 
       ConnexionLinkyStat.Close() 

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

     ExcelConnection.Close() 
+0

您是否確認這些列正在讀取在嘗試批量複製之前將它放入'objDR'中? – topshot

+0

@topshot是的,我確認objDR讀取所有列 – Elhendriks

+0

我假設列名完全相同,但可能試着'SqlBulkCopyColumnMapping'來確保。 – topshot

回答

0

我想這一個代碼,希望此代碼對你很有幫助項目

私人小組的button1_Click(BYVAL發件人爲System.Object的,BYVAL e As System.EventArgs)Handles Button1.Click

 Dim MyConnection As System.Data.OleDb.OleDbConnection 
    Dim DtSet As System.Data.DataSet 
    Dim MyCommand As System.Data.OleDb.OleDbDataAdapter 

    Dim fBrowse As New OpenFileDialog 
    With fBrowse 
     .Filter = "Excel files(*.xlsx)|*.xlsx|All files (*.*)|*.*" 
     .FilterIndex = 1 
     .Title = "Import data from Excel file" 
    End With 
    If fBrowse.ShowDialog() = Windows.Forms.DialogResult.OK Then 
     Dim fname As String 
     fname = fBrowse.FileName 
     MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source='" & fname & " '; " & "Extended Properties=Excel 8.0;") 
     MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection) 
     MyCommand.TableMappings.Add("Table", "Test") 
     DtSet = New System.Data.DataSet 
     MyCommand.Fill(DtSet) 
     MyConnection.Close() 
     For Each Drr As DataRow In DtSet.Tables(0).Rows 
      Execute_Local("INSERT INTO Excel(Name, Designation, Salary) VALUES ('" & Drr(0).ToString & "','" & Drr(1).ToString & "','" & Drr(2).ToString & "')") 
     Next 
     MsgBox("Successfully Saved") 

    End If 

End Sub`