SqlBulkCopy不会复制Excel工作表中的所有行

时间:2015-07-12 09:32:34

标签: sql-server vb.net sqlbulkcopy

我开发了一个Windows应用程序来导入Excel文件并将数据写入SQL Server数据库表。该应用程序运行良好,但它从第27或30行开始写入,有时从Excel工作表的第29行开始写入。我需要将所有行写入数据库表,从第1行到第4500行。

我的代码:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim fdlg As OpenFileDialog = New OpenFileDialog
    fdlg.Title = "Open File Dialog"
    fdlg.InitialDirectory = "C:\"
    fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
    fdlg.FilterIndex = 2
    fdlg.RestoreDirectory = True
    If fdlg.ShowDialog() = Windows.Forms.DialogResult.OK Then
        ExcelFileName = fdlg.FileName
    End If

    'Excel 2007
    Dim ExcelConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFileName + ";Extended Properties=""Excel 12.0 Xml;HDR=No;""")
    Try
        ExcelConnection.Open()
    Catch ex As Exception
    End Try

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

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

    Dim SQLconn As New SqlConnection()
    Dim ConnString As String = "Data Source=My_PC_Name;Initial Catalog=myDatabase;Integrated Security=True"
    SQLconn.ConnectionString = ConnString
    SQLconn.Open()

    Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(SQLconn)

        bulkCopy.DestinationTableName = "ItemDetails"

        Try
            objDR = objCmdSelect.ExecuteReader
            If objDR.HasRows = True Then
                bulkCopy.WriteToServer(objDR)
                MessageBox.Show("You Successfuly import the excel file")
                objDR.Close()
                SQLconn.Close()
            End If
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Using
End Sub

1 个答案:

答案 0 :(得分:0)

SQL是按订单定义的。因此,为了保证订单,您必须使用row_id添加辅助列(比如列A)。然后你可以使用它来选择你订购的数据。