Excel导入方式的行比预期的多

时间:2018-07-02 16:18:11

标签: excel vb.net import

使用下面的代码,我要导入一个包含5个工作表的excel文件,但是我只想要其中3个的数据。我得到的行数大约是预期的7倍。如何确保仅从每张纸中填充行?没有欺骗。

  Dim strConnection As String = ConfigurationManager.ConnectionStrings("conn").ToString
    Dim excelConnString As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Server.MapPath(excelFile) & "; Extended Properties=""Excel 12.0 Xml; HDR=Yes""")
    Dim conn As OleDbConnection = New OleDbConnection(excelConnString)
    Dim cmd As OleDbCommand = New OleDbCommand()
    cmd.Connection = conn
    Dim da As OleDbDataAdapter = New OleDbDataAdapter(cmd)
    Dim dt As DataTable = New DataTable()
    conn.Open()
    Dim dtSheet As DataTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)

    For Each sheet As System.Data.DataRow In dtSheet.Rows

        Dim sheetName As String = sheet("table_name").ToString()
        If sheetName = "UT$" Or sheetName = "XRAY$" Or sheetName = "FLANGE$" Then
            cmd.CommandText = "select * from [" & sheetName & "] WHERE [Drawing] Is Not NULL"
            da.SelectCommand = cmd
            da.Fill(dt)

            Dim myImportFinding As New ImportFinding

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

                If dt.Rows(i)("Platform") Is Nothing OrElse IsDBNull(dt.Rows(i)("Platform")) Then
                    myImportFinding.PLATFORM = ""
                Else
                    myImportFinding.PLATFORM = dt.Rows(i)("Platform")
                End If

1 个答案:

答案 0 :(得分:0)

是的,缺少了很多代码,但是重要的部分在那里。我决定重构并使其正常工作。每次循环浏览时,都要插入三个工作表中的所有行。我决定将实际的导入移至新方法中,并从每个工作簿的新数据表,命令和数据适配器开始。似乎现在工作正常。