Fastest way to export a Datagridview (VB.NET 2015) to MS Excel (2007)

  • Thread starter Thread starter CM16
  • Start date Start date
C

CM16

Guest
Hi. Firstly thanks for your time.
I am searching the way fastest to export a datagridview control to an MS Excel document.
I'm Use usea a method but this is too slow because my datagridiview cointains many columns and rows to traver recursively.
If i select the contain of the datagridview directly (with the properties multiselect=true and ClipBoarCopyMode=EnableWithAutoHeaderText) and paste this on a excel Worksheet the copy is soo fast.
Someone knows why?

This is the method that i am using

Thank's for you time, again.

Public Function GridAExcel(ByVal grd As DataGridView)
Dim fichero As New SaveFileDialog()
fichero.Filter = "Excel (*.xls)|*.xls"

Dim aplicacion As Microsoft.Office.Interop.Excel.Application
Dim libros_trabajo As Microsoft.Office.Interop.Excel.Workbook
Dim hoja_trabajo As Microsoft.Office.Interop.Excel.Worksheet
aplicacion = New Microsoft.Office.Interop.Excel.Application()
libros_trabajo = aplicacion.Workbooks.Add()



Dim Visibles As Integer = 0
For x = 0 To grd.Columns.Count - 1
If grd.Columns(x).Visible = True Then
Visibles = Visibles + 1
End If
Next
Dim NCol As Integer = grd.Columns.Count
Dim NRow As Integer = grd.RowCount


hoja_trabajo = DirectCast(libros_trabajo.Worksheets.Item(1), Microsoft.Office.Interop.Excel.Worksheet)
Dim Count = 1
For i As Integer = 1 To NCol
If grd.Columns(i - 1).Visible = True Then
hoja_trabajo.Cells.Item(1, Count) = grd.Columns(i - 1).Name
Count = Count + 1
End If

Next

hoja_trabajo.Rows.Item(1).Font.Bold = 1
hoja_trabajo.Rows.Item(1).HorizontalAlignment = 3
hoja_trabajo.Columns.AutoFit()

For i As Integer = 0 To grd.Rows.Count - 1
Dim cant As Integer = 1
For j As Integer = 0 To grd.Columns.Count - 1
If grd.Columns(j).Visible = True Then
hoja_trabajo.Cells(i + 2, cant) = grd.Rows(i).Cells(j).Value
cant = cant + 1
End If
Next
Next
aplicacion.Application.Visible = True

Return True
End Function

Continue reading...
 
Back
Top