Results 1 to 2 of 2

Thread: reading excel returns some rows as null

Threaded View

  1. #2
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,714

    Re: reading excel returns some rows as null

    Try the following syntax for reading your Sheet as shown in the attached VS2008 project which reads a Excel 2007 sheet where the first row has headers, IMEX=1

    Basic code
    Code:
    Public Class frmMainForm
        Private ExcelFileName As String = IO.Path.Combine(Application.StartupPath, "Products.xlsx")
        WithEvents bsProducts As New BindingSource
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim dtProducts As New DataTable
    
            Using cn As New OleDbConnection
                Dim Builder As New OleDbConnectionStringBuilder With _
                    { _
                        .DataSource = ExcelFileName, _
                        .Provider = "Microsoft.ACE.OLEDB.12.0" _
                    }
    
    
                Builder.Add("Extended Properties", "Excel 12.0; IMEX=1;HDR=Yes;")
    
                cn.ConnectionString = Builder.ConnectionString
    
                cn.Open()
    
                Using cmd As OleDbCommand = New OleDbCommand With {.Connection = cn}
                    '
                    ' Note that each column uses an alias. Of course we can
                    ' also use SELECT * FROM [Products$]
                    '
                    cmd.CommandText = _
                    <SQL>
                        SELECT 
                            ProductID As Identifier, 
                            ProductName As Product, 
                            QuantityPerUnit As Quantity 
                        FROM 
                            [Products$]
                    </SQL>.Value
    
                    Dim dr As System.Data.IDataReader = cmd.ExecuteReader
                    dtProducts.Load(dr)
                    dtProducts.Columns("Identifier").ColumnMapping = MappingType.Hidden
                    bsProducts.DataSource = dtProducts
                    DataGridView1.DataSource = bsProducts
                    DataGridView1.AutoResizeColumns()
    
                    Dim Position As Integer = bsProducts.Find("Product", "Alice Mutton")
    
                    If Position > -1 Then
                        bsProducts.Position = Position
                    End If
    
                End Using
    
            End Using
        End Sub
    End Class
    Attached Files Attached Files

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