Está en la página 1de 5

50 - Exportar los datos de un ListView a Excel

<Volver> - Anterior - Siguiente

La siguiente funcin exporta los datos de un control ListView a una hoja de Excel y muestra el progreso en un control ProgressBar
Vista del formulario de ejemplo

Hay una funcin llamada Exportar_Excel a la cual se le debe pasar el path y el nombre del Libro. El segundo parmetro es el control ListView, el tercer parmetro es opcional y es para el Progressbar, el ltimo parmetro es el ndice de la hoja. Por ejemplo : Call Exportar_Excel("c:\libro.xls", ListView1, ProgressBar1, 2)

Nota . para exportar los datos en un libro nuevo, sin tener que indicar un libro existente, se puede ejecutar el mtodo Add sin ningn parmetro. Es decir en vez de utilizar el mtodo Open, utilizar el mtodo Add del objeto WorkBooks de la siguiente forma: Set obj_Libro = .Workbooks.Add

Ejemplo

Agregar un control command Un ListView Un Progressbar Especificar la ruta del libro de Excel Indicar en el ltimo argumento el ndice de la hoja, por defecto si no se indica, se exportarn los datos en la hoja nmero 1

Cdigo fuente en un Formulario: Texto planoImprimir 1. Option Explicit 2. 3. 4. ' -----------------------------------------------------------------5. ' \\ -- Funcin para exportar los datos 6. ' -----------------------------------------------------------------7. Function Exportar_Excel( _ 8. sFileName As String, _ 9. ListView As ListView, _ 10. Optional Progressbar As Progressbar, _ 11. Optional SheetIndex As Integer = 1) As Boolean 12. 13. On Error GoTo error_Handler 14. 15. Dim obj_Excel As Object ' -CREAR EL OBJETO (INSTANCIAR)CON EL OBJETO APLICACION (obj_Exc el) 16. Dim obj_Libro As Object 17. 18. Dim iCol As Integer ' -- Variables para las columnas y filas 19. Dim iRow As Integer 20. 21. ' -- Nueva referencia a Excel y nuevo referencia al Libro 22. Set obj_Excel = CreateObject("Excel.Application")

23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69.

With obj_Excel ' -- Abrir el libro Set obj_Libro = .Workbooks.Open(sFileName) End With With obj_Libro ' -- Asignamos El valor Maximo del Progress teniendo ' -- como dato la cantidad de items en el ListView If Not Progressbar Is Nothing Then Progressbar.Max = ListView.ListItems.Count If Not Progressbar.Visible Then Progressbar.Visible = True End If ' -- Referencia a la hoja con ndice 1 With .Sheets(SheetIndex) ' -- Recorremos la cantidad de items del ListView For iRow = 1 To ListView.ListItems.Count iCol = 1 ' -- Asignamos el item actual en la celda .Cells(iRow, iCol) = ListView.ListItems.Item(iRow) ' -- Asignamos el subitem actual en la celda For iCol = 1 To ListView.ColumnHeaders.Count - 1 .Cells(iRow, iCol + 1) = ListView.ListItems(iRow).SubItems(iCol) Next If Not Progressbar Is Nothing Then ' -- Aumentamos en 1 la propiedad value Progressbar.Value = Progressbar.Value + 1 End If Next End With End With ' -- Destruimos las variables de objeto obj_Excel.Visible = True Set obj_Libro = Nothing Set obj_Excel = Nothing ' -- Ok Exportar_Excel = True If Not Progressbar Is Nothing Then Progressbar.Value = 0 Progressbar.Visible = False End If

70. 71. ' -- Errores 72. Exit Function 73. error_Handler: 74. 75. Exportar_Excel = False 76. MsgBox Err.Description, vbCritical 77. 78. On Error Resume Next 79. Set obj_Libro = Nothing 80. Set obj_Excel = Nothing 81. 82. Progressbar.Value = 0 83. End Function 84. 85. 86. ' -----------------------------------------------------------------87. ' \\ -- Botn para exportar los datos al libro 88. ' -----------------------------------------------------------------89. Private Sub Command1_Click() 90. 91. Dim ret As Boolean 92. 93. ' -- Le pasa el path donde est ubicado el libro, _ 94. -- el control ListView, opcional un Progressbar, _ 95. -- y lo exporta en la hoja con ndice 2 96. ret = Exportar_Excel("c:\libro1.xls", ListView1, ProgressBar1, 2) 97. 98. If ret Then 99. ' -- OK 100. MsgBox " Datos exportados a Excel OK ", vbInformation 101. End If 102. 103. End Sub 104. ' -----------------------------------------------------------------105. ' \\ -- Inicio 106. ' -----------------------------------------------------------------107. 108. Private Sub Form_Load() 109. 110. Dim lvItem As ListItem 111. Dim i As Integer 112. 113. ' -- Configurar ListView 114. With ListView1 115. .ColumnHeaders.Add , , " Columna 1 " 116. .ColumnHeaders.Add , , " Columna 2 "

117. 118. 119. 120. 121. 122. 123. 124. 125. 126. 127. 128. 129. 130. 131. 132. 133. 134.

.View = lvwReport End With ' -- Aadir algunos items al listview For i = 0 To 5000 Set lvItem = ListView1.ListItems.Add(, , " Item " & i) lvItem.SubItems(1) = "subitem " & i Next Command1.Caption = " > Exportar Listview a Excel "

End Sub ' -----------------------------------------------------------------' \\ -- Redimensionar controles ' -----------------------------------------------------------------Private Sub Form_Resize() With ListView1 .Move 0, 0, Me.ScaleWidth, Me.ScaleHeight (Command1.Height + 50) 135. Command1.Move Me.ScaleWidth (Command1.Width + 50), .Top + .Height + 50 136. End With 137. With Command1 138. ProgressBar1.Move 0, .Top, Me.ScaleWidth - (.Width + 100), .Height 139. End With 140. End Sub

También podría gustarte