Results 1 to 2 of 2

Thread: Selecting the first sheet in an Excel workbook

  1. #1

    Thread Starter
    Member
    Join Date
    Jun 2004
    Location
    The Netherlands
    Posts
    37

    Selecting the first sheet in an Excel workbook

    When accessing Excel data I use;

    MyCommand = New System.Data.OleDb.OleDbDataAdapter( _
    "select * from [Sheet1$]", MyConnection)

    All help files etc. I've read till now use this to select all data from the sheet with name "Sheet1", but I do not know the name of the sheet, so is there a way to select the first sheet no matter it's name?

  2. #2
    Hyperactive Member CyberHawke's Avatar
    Join Date
    May 2004
    Location
    Washington DC
    Posts
    477
    This works:
    VB Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    2.         Dim dtSchema As DataTable
    3.         Dim drSchema As DataRow
    4.         Dim strForTextBox As String
    5.         Dim strTableName As String
    6.         Dim strSelect As String = "SELECT * FROM [{0}]"
    7.         Dim da As New OleDbDataAdapter
    8.         Dim ds As New DataTable
    9.         Dim fDlg As New OpenFileDialog
    10.         fDlg.Filter = "Excel Spreadsheets (*.xls)|*.xls"
    11.         fDlg.ShowDialog()
    12.         If fDlg.FileName.Length > 0 Then
    13.             Dim cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
    14.                                                   "Data Source=" & fDlg.FileName & _
    15.                                                   ";Extended Properties=Excel 8.0;")
    16.  
    17.             cn.Open()
    18.             dtSchema = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})
    19.  
    20.             'DataGrid1.SetDataBinding(dtSchema, "")
    21.             drSchema = dtSchema.Rows(0)
    22.             strTableName = drSchema("TABLE_NAME")
    23.             Dim cmd As New OleDbCommand(String.Format(strSelect, strTableName))
    24.             cmd.Connection = cn
    25.             da.SelectCommand = cmd
    26.             da.Fill(ds)
    27.             'For Each drSchema In dtSchema.Rows
    28.             '    strForTextBox = strForTextBox & "Table name = " & drSchema("TABLE_NAME") & vbCrLf
    29.             'Next
    30.             DataGrid1.DataSource = ds
    31.  
    32.             'TextBox1.Text = strForTextBox
    33.  
    34.             cn.Close()
    35.             cn.Dispose()
    36.         End If
    37.     End Sub

    I just love a challenge
    Whadayamean it doesn't work....
    It works fine on my machine!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width