DataGridView Export with headers

Hi Experts

I am trying to get my datagridview to export with headers
I have tried to get it right but to no avail.

Private Sub BtnExport2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnExport2.Click
 Dim xlApp As Excel.Application
        Dim xlWorkBook As Excel.Workbook
        Dim xlWorkSheet As Excel.Worksheet
        Dim misValue As Object = System.Reflection.Missing.Value

        Dim i As Int16, j As Int16

        'xlApp = New Excel.ApplicationClass
        xlApp = New Excel.Application()
        xlWorkBook = xlApp.Workbooks.Add(misValue)
        xlWorkSheet = xlWorkBook.Sheets("sheet1")

         For c As Integer = 0 To DataGridViewPerformance.Columns.Count - 1
            xlWorkSheet.Cells(1, c + 1).Value = DataGridViewPerformance.Columns(c).HeaderText
        Next

        For i = 0 To DataGridViewPerformance.RowCount - 2
            For j = 0 To DataGridViewPerformance.ColumnCount - 1
                xlWorkSheet.Cells(i + 1, j + 1) = DataGridViewPerformance(j, i).Value.ToString()
            Next
        Next

        xlWorkBook.SaveAs("c:\Performance.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, _
         Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue)
        xlWorkBook.Close(True, misValue, misValue)
        xlApp.Quit()

        releaseObject(xlWorkSheet)
        releaseObject(xlWorkBook)
        releaseObject(xlApp)

        MessageBox.Show("Your File is successfully saved")
    End Sub

Open in new window


Can someone please take a look at this code and steer me right?

Thanks
GrahamSAAsked:
Who is Participating?
 
Miguel OzSoftware EngineerCommented:
Your issue is that you are overriding the header line: (notice (i+2) change)
Replace this line:
xlWorkSheet.Cells(i + 1, j + 1) = DataGridViewPerformance(j, i).Value.ToString()

with:
xlWorkSheet.Cells(i + 2, j + 1) = DataGridViewPerformance(j, i).Value.ToString()
0
 
GrahamSAAuthor Commented:
Perfect Friend
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.