I have code that is supposed to include header text when exporting to Excel.
For i As Integer = 0 To DataGridView2.Rows.Count - 2
For j As Integer = 0 To DataGridView2.Columns.Count - 1
' Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check.
If cellRowIndex = 1 Then
worksheet.Cells(cellRowIndex, cellColumnIndex) = DataGridView2.Columns(j).HeaderText
Else
worksheet.Cells(cellRowIndex, cellColumnIndex) = DataGridView2.Rows(i).Cells(j).Value
End If
cellColumnIndex += 1
Next
cellColumnIndex = 1
cellRowIndex += 1
Next
However, this code replaces the first data row with the header text instead of inserting it above. If I remove the If statement which extracts the header text, I get all rows out, but I don't get header text.
For i As Integer = 0 To DataGridView2.Rows.Count - 2
For j As Integer = 0 To DataGridView2.Columns.Count - 1
worksheet.Cells(cellRowIndex, cellColumnIndex) = DataGridView2.Rows(i).Cells(j).Value
cellColumnIndex += 1
Next
cellColumnIndex = 1
cellRowIndex += 1
Next
Any ideas on how to solve this?
After tracing your code it is clear you are having an indexing problem in the two
forloops. It appears the code you supplied is missing the first row of data.As you commented:
This is not correct, it is not replacing the row it is simply skipping the first row of data in the
DataGridView. Below is your code to explain.Basically this loops through the rows then the columns. The problem is in the
Ifstatement and the indexi. In thisIfstatement you check to see if this is the first time around to get the headers. If it is the first time around you write the headers to excel and proceed. This is going to skip the first row of data because the loop variableiis used as an index into the DataGridView rows with the assignment:When entering the
jloop the first time aroundiis zero (0). A check is made withcellRowIndexto determine if the headers need to be output. In this case they do… the headers are output then exit thisifand loop back up to the next header. When all headers are output you exit thejloop and loop back up to theiloop. This will incrementito 1 and enter thejloop… Sinceihas already been 0 when the headers were output we will skip/miss row 0 in theDataGridView. I hope this makes sense.A simple solution for what you have would be to simply start
iat -1 with:This will solve the problem you are having however the code is not easy to follow. I recommend using a
foreachloop for looping through theDataGridViewrows and separating the column output from the rows output. This does create two loops but the first loop will only loop once to add the headers. The next loop goes through all the rows. This will make indexing easier to handle and easier to read in the future.Hope this helps.