Tuesday, February 28, 2012

VB.NET - Exporting DataGridView to Excel

If you want to export the entire contents of a DataGridView to excel the code snippet is:

...


Dim i As Integer
Dim j As Integer


xlWorkSheet.Range("A1").Select()

            'write the rest of the data into excel starting on row 3
            For i = 0 To   DataGridView1 .RowCount - 1
                For j = 0 To DataGridView1.ColumnCount - 1
                    xlWorkSheet.Cells(i + 3, j + 1) =   DataGridView1 (j, i).Value.ToString()
                Next
            Next
...



If you want to export just the selected rows of a DataGridView to excel the code snippet is:

...


Dim i As Integer
Dim j As Integer

Dim y as integer = 1

'write the rest of the data into excel starting on row 3
            For i = 0 To gridDGV.SelectedRows.Count - 1

                For j = 0 To gridDGV.ColumnCount - 1

                    xlWorkSheet.Cells(i + 3, j + 1) = gridDGV(j, gridDGV.SelectedRows(gridDGV.SelectedRows.Count - y).Index).Value.ToString()
                Next
                y += 1
            Next

...