A1VBCode Forums

Visual Basic: Missing column headings when exporting gridview to excel


http://a1vbcode.com/vbforums/Topic32182.aspx

By newbie001 - 7/31/2014

Hello Everyone,



I am new to Visual basic 2008 and trying to export gridview to excel. I am able to export the data content of the grid to excel, apart from the columns i.e id, name etc





Could you please guide me on what I am doing wrong?





I am able to see the column headings in message as mentioned in the below code (under Export button)





But, I am not able to insert the text message into the excel 1st row.







The code for the "Export" button that I am using is as follows:





Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click



Dim ExcelApp As Object, ExcelBook As Object

Dim ExcelSheet As Object

Dim i As Integer

Dim j As Integer



'create object of excel

ExcelApp = CreateObject("Excel.Application")

ExcelBook = ExcelApp.WorkBooks.Add

ExcelSheet = ExcelBook.WorkSheets(1)



With ExcelSheet



'Able to see the column headings in message

For Each col As DataGridViewColumn In DataGrid.Columns



MessageBox.Show(col.HeaderText)





For i = 1 To Me.DataGrid.RowCount

.cells(i, 1) = Me.DataGrid.Rows(i - 1).Cells("IDDataGridViewTextBoxColumn").Value

For j = 1 To DataGrid.Columns.Count - 1

.cells(i, j + 1) = DataGrid.Rows(i - 1).Cells(j).Value



Next

Next

End With

ExcelApp.Visible = True

'

ExcelSheet = Nothing

ExcelBook = Nothing

ExcelApp = Nothing





End Sub







Thanks for your help in advance :-)