Click here to Skip to main content
15,885,890 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I have used the following code to extract the datagridview contents to an excel sheet. But the thing is i can't able to get the column headers in the excel sheet. Please assist me to get the column header in the excel sheet.
VB
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
     For i = 1 To Me.DataGridView1.RowCount
           .cells(i, 1) = Me.DataGridView1.Rows(i - 1).Cells("id").Value
           For j = 1 To DataGridView1.Columns.Count - 1
               .cells(i, j + 1) = DataGridView1.Rows(i - 1).Cells(j).Value
           Next
     Next
End With

ExcelApp.Visible = True
'
ExcelSheet = Nothing
ExcelBook = Nothing
ExcelApp = Nothing
Posted
Updated 18-Jun-19 20:27pm
v2

1 solution

Before you loop through all the rows in your DataGridView, loop through all the Columns and add the headertext to the ExcelSheet.
VB
With ExcelSheet
   For Each column As DataGridViewColumn In DataGridView1.Columns
      .cells( 1, column.Index + 1 ) = column.HeaderText
   Next 
   For i = 1 To Me.DataGridView1.RowCount
      .cells(i + 1, 1) = Me.DataGridView1.Rows(i - 1).Cells("id").Value
      For j = 1 To DataGridView1.Columns.Count - 1
         .cells(i + 1, j + 1) = DataGridView1.Rows(i - 1).Cells(j).Value
      Next
   Next
End With
 
Share this answer
 
Comments
Member 14969413 25-Oct-20 5:56am    
thank you for this. really helped my problem.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900