Exportar un DataGrid a Excel

2089 vistas

El siguiente código es una manera de exportar los datos de un DataGrid a una hoja Excel, no obstante. No es recomendable para un volumen para un gran volumen de datos.

Suponemos que se ha rellenado anteriormente el DataGrid "DataGrid1" con el DataSet "ds" que contiene un DataTable "da".

Tendremos que añadir una referencia a "Microsoft Excel 11.0 Object Library"



vbnet
  1. Dim xlApp As Excel.Application
  2. Dim xlBook As Excel.Workbook
  3. Dim xlSheet As Excel.Worksheet
  4.  
  5. xlApp = CType(CreateObject("Excel.Application"), Excel.Application)
  6. xlBook = CType(xlApp.Workbooks.Add, Excel.Workbook)
  7. xlSheet = CType(xlBook.Worksheets(1), Excel.Worksheet)
  8.  
  9. ' contamos el número de líneas y de columnas del DataTable
  10. Dim nbrLigne As Integer = ds.Tables("da").Rows.Count - 1
  11. Dim nbrColon As Integer = ds.Tables("da").Columns.Count - 1
  12. Dim x, y As Integer
  13.  
  14. For x = 0 To nbrColon
  15.   ' cogemos el título de la columna del DataTable
  16.   xlSheet.Cells(1, x + 1) = ds.Tables("da").Columns(x).ColumnName
  17.   ' ponemos la primera línea en negrita
  18.   xlSheet.Rows(1).Font.Bold = True
  19.  
  20.   ' por cada columna y cada línea, exportamos los datos
  21.   For y = 0 To nbrLigne
  22.         xlSheet.Cells(y + 2, x + 1) = DataGrid1.Item(y, x)
  23.   Next
  24. Next
  25.  
  26. ' mostramos el resultado del Excel
  27. xlSheet.Application.Visible = True
  28. ' podemos guardar el documento
  29. xlSheet.SaveAs("C:\nombre_documento.xls")
  30. ' cerramos la aplicación y destruimos los objetos
  31. xlApp.Quit()
  32. xlSheet = Nothing
  33. xlBook = Nothing
  34. xlApp = Nothing