Importing ms excel data to datagrid. first row is column names in dg
I am using the following code to import msexcel data and put it in a data grid. It all works well except that the first row of data is assumed to be the column names. So I lose the first row of data. Anyone know how i can fix this?
Private Function GetData()
Dim myFile As String
'Dim dt As System.Data.DataTable
Dim openFileDialog1 As New OpenFileDialog
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
Dim MyConnection As System.Data.OleDb.OleDbConnection
openFileDialog1.InitialDirectory = "c:\mcmcom\chambers\ptsdatabase\"
openFileDialog1.Filter = ".xls files (*.xls)|*.xls|All files (*.*)|*.*"
openFileDialog1.FilterIndex = 2
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = DialogResult.OK Then
myFile = openFileDialog1.FileName
End If
Try
MyConnection = New System.Data.OleDb.OleDbConnection( _
"provider=Microsoft.Jet.OLEDB.4.0; " & _
"data source= " & myFile & "; Extended Properties=Excel 8.0;")
' Select the data from Sheet1 of the workbook.
MyCommand = New System.Data.OleDb.OleDbDataAdapter( _
"select * from [Sheet1$]", MyConnection)
dt = New System.Data.DataTable
MyCommand.Fill(dt)
So basically it fills the datagrid, but the column header names are the values of the first record. If i set the datagrid properties to No column headers, i just lose the first record!
Its annoying
mcm
Re: Importing ms excel data to datagrid. first row is column names in dg
I found a simple solution,
1.create a new row,
2.copy values from header to new row,
3.rename header names
4.insert new row to table at pos index 0
MyCommand.Fill(DtSet)
myDataRow = DtSet.Tables(0).NewRow()
For i = 0 To DtSet.Tables(0).Columns.Count - 1
myDataRow(i) = DtSet.Tables(0).Columns(i).Caption
DtSet.Tables(0).Columns(i).ColumnName = CStr(i)
Next
DtSet.Tables(0).Rows.InsertAt(myDataRow, 0)