0

我想上传一个 Excel 文件并将数据写入 sql server 2008。

Excel 文件有 7 张纸,它写在 7 个表格中。
示例 : (sheetn -> temp_sheetn)

代码运行良好,但最后一张表没有写在最后一张表中。

代码是这样的:

Partial Class app_UploadData
    Inherits System.Web.UI.Page
    Dim apps As New MyApps
    Dim GlobReg As Integer = 0
    Dim GlobOTC As Integer = 0

    Private dt As DataTable = Nothing

    Public Function xlsInsert(ByVal pth As String) As System.Data.DataTable
        Dim strcon As String = String.Empty
        If Path.GetExtension(pth).ToLower().Equals(".xls") OrElse Path.GetExtension(pth).ToLower().Equals(".xlsx") Then
            strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & pth & ";Extended Properties=""Excel 8.0;HDR=YES;"""
        Else
            strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & pth & ";Extended Properties=""Excel 12.0;HDR=YES;"""
        End If
        Dim strselect As String = "Select * from [Sheet1$]"
        Dim exDT As New DataTable()
        Using excelCon As New OleDbConnection(strcon)
            Try
                excelCon.Open()
                Using exDA As New OleDbDataAdapter(strselect, excelCon)
                    exDA.Fill(exDT)
                End Using
            Catch oledb As OleDbException
                Throw New Exception(oledb.Message.ToString())
            Finally
                excelCon.Close()
            End Try
            For i As Integer = 0 To exDT.Rows.Count - 1
                ' Check if first column is empty
                ' If empty then delete such record
                If exDT.Rows(i)("CardNo").ToString() = String.Empty Then
                    exDT.Rows(i).Delete()
                End If
            Next
            exDT.AcceptChanges()
            ' refresh rows changes
            If exDT.Rows.Count = 0 Then
                Throw New Exception("File uploaded has no record found.")
            End If
            Return exDT
        End Using
    End Function

    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim ds As New DataSet()
        Dim XlsConnString As String = String.Empty


        Dim DirPath As String = Server.MapPath("~/Temp_Upload/")
        Dim fName As String

        If (Directory.Exists(DirPath)) Then
            For Each fName In Directory.GetFiles(DirPath)
                If File.Exists(fName) Then                    
                    File.Delete(fName)
                End If
            Next
        End If

        If xlsUpload.HasFile Then
            Dim fileName As String = Path.GetFileName(xlsUpload.PostedFile.FileName)
            Dim fileExtension As String = Path.GetExtension(xlsUpload.PostedFile.FileName)
            Dim fileLocation As String = Server.MapPath("~/Temp_Upload/" & fileName)
            xlsUpload.SaveAs(fileLocation)

            'Check whether file extension is xls or xslx
            If fileExtension = ".xls" Then
                XlsConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & fileLocation & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=2"""
            ElseIf fileExtension = ".xlsx" Then
                XlsConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & fileLocation & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
            ElseIf fileExtension <> ".xls" Or fileExtension <> ".xlsx" Then
                lblMessage.Text = "Upload file must be excel !"
                Exit Sub
            End If

            Dim cmd As New SqlCommand : Dim SheetName As String 'Dim dr As SqlDataReader
            'Dim tran As SqlTransaction

            apps.OpenConnection()
            cmd.Connection = apps.oConn

            Dim cn As New OleDbConnection(XlsConnString)
            Try
                cn.Open()
            Catch ex As OleDbException
                Console.WriteLine(ex.Message)
            Catch ex As Exception
                Console.WriteLine(ex.Message)
            End Try

            ' It Represents Excel data table Schema.
            Dim dt As New System.Data.DataTable()
            dt = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
            If dt IsNot Nothing OrElse dt.Rows.Count > 0 Then
                For sheet_count As Integer = 1 To dt.Rows.Count - 1
                    Try
                        ' Create Query to get Data from sheet.
                        SheetName = dt.Rows(sheet_count)("table_name").ToString()
                        'Dim da As New OleDbDataAdapter("SELECT * FROM [" & sheetname & "]", cn)
                        'da.Fill(ds, sheetname)

                        'Execute a query to erase any previous data from our destination table                        
                        cmd.CommandText = "Truncate Table Temp_" & SheetName
                        cmd.ExecuteNonQuery()

                        'Series of commands to bulk copy data from the excel file into our SQL table
                        Dim OleDbConn As OleDbConnection = New OleDbConnection(XlsConnString)
                        Dim OleDbCmd As OleDbCommand = New OleDbCommand(("SELECT * FROM [" & SheetName & "]"), OleDbConn)
                        'Dim OleDbCmd As OleDbCommand = New OleDbCommand(("SELECT * FROM [Customer$]"), OleDbConn)
                        OleDbConn.Open()
                        Dim OleDbRead As OleDbDataReader = OleDbCmd.ExecuteReader()

                        Dim bulkCopy As SqlBulkCopy = New SqlBulkCopy(apps.oConn)
                        bulkCopy.DestinationTableName = "Temp_" & SheetName
                        bulkCopy.WriteToServer(OleDbRead)

                        OleDbConn.Close()
                        OleDbConn = Nothing

                    Catch ex As DataException
                        Console.WriteLine(ex.Message)
                    Catch ex As Exception
                        Console.WriteLine(ex.Message)
                    End Try
                Next
            End If

            cn.Close()
            cn = Nothing

            apps.CloseConnection()

        End If


    End Sub

End Class
4

1 回答 1

1

读取的行

For sheet_count As Integer = 1 To dt.Rows.Count - 1

应该是

For sheet_count As Integer = 0 To dt.Rows.Count - 1

或者

For sheet_count As Integer = 1 To dt.Rows.Count

我怀疑第一个,但我不记得这是否是一个从零开始的列表,因为我没有在这里安装 VB.Net。

顺便说一句,无需检查文件扩展名是否为 .xls,然后使用 Jet 提供程序,Microsoft.ACE.OLEDB.12.0 就可以在 .xls 文件上正常工作。

于 2013-01-01T13:37:54.453 回答