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

前端 未结 9 624
青春惊慌失措
青春惊慌失措 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:33

    You can use this approach also for getting sheet name. See comments for more understanding

    myExcelConn.Open()
    
    //GET DATA FROM EXCEL SHEET.
    Dim str As String = String.Empty
    Dim Sheets As DataTable = myExcelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
    For i As Integer = 0 To Sheets.Rows.Count - 1
        str += Sheets.Rows(i)("TABLE_NAME").ToString() + "," //It will return sheet1,sheet2,sheet3 according to my excel file
    Next
    
    Dim objOleDB As New OleDbCommand("SELECT *FROM [" + str.Split(",")(0) + "]", myExcelConn) //It will select sheet1
    Me.Label1.Text = str.Split(",")(0).Replace("$", "")
    // READ THE DATA EXTRACTED FROM THE EXCEL FILE.
    Dim objBulkReader As OleDbDataReader
    objBulkReader = objOleDB.ExecuteReader
    
    Dim dt As DataTable = New DataTable
    dt.Load(objBulkReader)
    
    //FINALLY, BIND THE EXTRACTED DATA TO THE GRIDVIEW.
    GridView1.DataSource = dt
    GridView1.DataBind()
    //If you want sheet2 data
     Dim objOleDB1 As New OleDbCommand("SELECT *FROM [" + str.Split(",")(1).Split(",")(0) + "]", myExcelConn)
    //If you want sheet3 data
     Dim objOleDB2 As New OleDbCommand("SELECT *FROM [" + str.Split(",")(2).Split(",")(0) + "]", myExcelConn)
    

提交回复
热议问题