Getting the first sheet from an Excel document regardless of sheet name with OleDb

前端 未结 9 694
青春惊慌失措
青春惊慌失措 2020-12-29 02:23

I have users that name their sheets all sorts of crazy things, but I want to be able to get the first sheet of the Excel document regardless of what it is named.

I

9条回答
  •  难免孤独
    2020-12-29 02:35

    This code has worked fine where i have used the data grid "DataGridView1" to load all the content of the sheet

    Dim MyConnection As System.Data.OleDb.OleDbConnection
    Dim DtSet As System.Data.DataSet : Dim filteext As String = ""
    
     ''check for the file type
     If IO.Path.GetExtension(fileName) = "xls" Then
                    filteext = "Excel 8.0"
     ElseIf IO.Path.GetExtension(fileName) = ".xlsx" Then
                    filteext = "Excel 12.0"
     End If
    
    ''open connection
    
     MyConnection = New System.Data.OleDb.OleDbConnection _
                   ("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & fileName & "';Extended Properties=" & filteext & ";")
                MyConnection.Open()
    
      Dim myTableName = MyConnection.GetSchema("Tables").Rows(0)("TABLE_NAME")
    
      Dim MyCommand As OleDbDataAdapter = New OleDbDataAdapter(String.Format("SELECT * FROM [{0}]", myTableName), MyConnection)
    
    
       MyCommand.TableMappings.Add("Table", "TestTable")
                DtSet = New System.Data.DataSet
    
        MyCommand.Fill(DtSet)
    
        DataGridView1.DataSource = DtSet.Tables(0)
                'DtSet.DataSetName. 
    
        MyConnection.Close()
    

提交回复
热议问题