Visual Basic.NET - Ayuda para exportar datos de datagrid a excel

 
Vista:

Ayuda para exportar datos de datagrid a excel

Publicado por Veronica (28 intervenciones) el 05/11/2009 15:03:39
Hola a todos:
Estoy creando una aplicación en VB 2005 y necesito importar los datos de un datagridview a excel; es importante llevar los encabezados de cada columna y luego las filas con sus respectivos datos.
¿Alguien podría ayudarme con esto?...¿podrían proporcionarme algún tipo de código q me ayudara?
Muchas gracias
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

RE:Ayuda para exportar datos de datagrid a excel

Publicado por MIRIAM (2 intervenciones) el 05/11/2009 18:45:52
Hola Veronica, tengo uno muy bueno espero te sirva, lo tengo para office 2007 , este lo tome de las aportaciones del guille.

si tienes duda me dices

'incluyes las referencias
microsoft excel 12.0 object library
microsoft office 12.0 object library

´'incluyes este -> Imports Microsoft.Office.Interop


'dgq <- es el nombre de mi data grid

Dim fila, columna, f, c, c1, f1 As Integer
fila = dgq.RowCount
columna = dgq.ColumnCount

Dim oExcel As Excel.ApplicationClass
Dim oBooks As Excel.Workbooks
Dim oBook As Excel.WorkbookClass
Dim oSheet As Excel.Worksheet

' Inicia Excel y abre el workbook
oExcel = CreateObject("Excel.Application")
oExcel.Visible = True
oBooks = oExcel.Workbooks
oBook = oExcel.Workbooks.Add
oSheet = oBook.Sheets(1)

'oBook = oBooks.Open( _
' "C:\DevCare\DevCareExcelAutomation\Data.xls")

Const ROW_FIRST = 1
Dim iRow As Int64 = 1

' Encabezado
oSheet.Cells(ROW_FIRST, 1) = "No_Caso"
oSheet.Cells(ROW_FIRST, 2) = "Atraso(Dias)"
oSheet.Cells(ROW_FIRST, 3) = "Tipo_Queja"
oSheet.Cells(ROW_FIRST, 4) = "Servicio"
oSheet.Cells(ROW_FIRST, 5) = "Queja"
oSheet.Cells(ROW_FIRST, 6) = "Status"
oSheet.Cells(ROW_FIRST, 7) = "Llamada_E"
oSheet.Cells(ROW_FIRST, 8) = "Llamada_S"
oSheet.Cells(ROW_FIRST, 9) = "Contacto"
oSheet.Cells(ROW_FIRST, 10) = "Cliente"
oSheet.Cells(ROW_FIRST, 11) = "Usuario"
oSheet.Cells(ROW_FIRST, 12) = "F_Alta"
oSheet.Cells(ROW_FIRST, 13) = "F_Modificacion"

oSheet.Cells(ROW_FIRST, 1).font.bold = True
oSheet.Cells(ROW_FIRST, 2).font.bold = True
oSheet.Cells(ROW_FIRST, 3).font.bold = True
oSheet.Cells(ROW_FIRST, 4).font.bold = True
oSheet.Cells(ROW_FIRST, 5).font.bold = True
oSheet.Cells(ROW_FIRST, 6).font.bold = True
oSheet.Cells(ROW_FIRST, 7).font.bold = True
oSheet.Cells(ROW_FIRST, 8).font.bold = True
oSheet.Cells(ROW_FIRST, 9).font.bold = True
oSheet.Cells(ROW_FIRST, 10).font.bold = True
oSheet.Cells(ROW_FIRST, 11).font.bold = True
oSheet.Cells(ROW_FIRST, 12).font.bold = True
oSheet.Cells(ROW_FIRST, 13).font.bold = True

oSheet.Columns(1).ColumnWidth = 10
oSheet.Columns(2).ColumnWidth = 40
oSheet.Columns(3).ColumnWidth = 30
oSheet.Columns(4).ColumnWidth = 15
oSheet.Columns(5).ColumnWidth = 40
oSheet.Columns(6).ColumnWidth = 15
oSheet.Columns(7).ColumnWidth = 40

' Loop que almacena los datos
'Dim rowCustomer As dsCustomers.CustomersRow
f1 = 0
For f = 2 To fila
c1 = 1
For c = 0 To columna - 1
oSheet.Cells(f, c1) = dgq(c, f1).Value
c1 = c1 + 1
Next c
f1 = f1 + 1
Next f

oSheet.Cells.Select()
oSheet.Cells.EntireColumn.AutoFit()
oSheet.Columns(5).ColumnWidth = 30
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

RE:Ayuda para exportar datos de datagrid a excel

Publicado por gon (31 intervenciones) el 05/11/2009 18:54:47
hola, te paso otro ejemplo

Sub ExportarAExcel(ByVal xgridexpo As DataGridView)
Dim strStreamW As Stream
Dim strStreamWriter As StreamWriter
Dim Filas = xgridexpo.Rows.Count
Dim Columnas = xgridexpo.Columns.Count
Dim Archivo As String = Application.StartupPath & "\Centros.csv"
Dim Linea As String = ""
Dim f As Integer
Dim c As Integer

File.Delete(Archivo)
strStreamW = File.OpenWrite(Archivo)

strStreamWriter = New StreamWriter(strStreamW, System.Text.Encoding.UTF8)

'CABECERA
For c = 0 To Columnas - 4
Linea = Linea & xgridexpo.Columns(c).Name & ";"
Next

Linea = Mid(Linea, 1, Linea.ToString.Length - 1)
strStreamWriter.WriteLine(Linea)
Linea = Nothing

'FILAS
For f = 0 To Filas - 1
For c = 0 To Columnas - 4
Linea = Linea & xgridexpo.Item(c, f).Value & ";"
'MsgBox(Grid.Item(c, f).Value)
Next
Linea = Mid(Linea, 1, Linea.ToString.Length - 1)
strStreamWriter.WriteLine(Linea)
Linea = Nothing
Next
strStreamWriter.Close()

Try
Process.Start(Archivo) 'Ejecuta el archivo creado
Catch Ex As Exception
MsgBox(Ex.Message, MsgBoxStyle.Critical, Ex.Source)
End Try
aEXCEL = False
End Sub
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Ayuda para exportar datos de datagrid a excel

Publicado por Veronica (28 intervenciones) el 06/11/2009 13:50:26
¡Muchas gracias a ambos!...ahora mismo pongo manos a la obra y les cuento q salio.
Saludos!
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Ayuda para exportar datos de datagrid a excel

Publicado por Alejandro (15 intervenciones) el 06/11/2009 17:43:51
Que tal, te paso un codigo que a mi me ayudo bastante, es facil de entender.

Public Function GridAExcel()
'***** PRUEBAS PARA MANDAR UN DGV A EXCEL : ALEX *****

'Creamos las variables
Dim exApp As New Excel.Application 'Se debe agregar la referencia en el proyecto para usar esta función
Dim exLibro As Excel.Workbook
Dim exHoja As Excel.Worksheet
' Variables para # de columnas y # de renglones
Dim iCol As Integer
Dim iRow As Integer

Try
'Añadimos el Libro al programa, y la hoja al libro

exLibro = exApp.Workbooks.Add
exHoja = exLibro.Worksheets.Add()

iCol = Go_Grid.Columns.Count 'MiDato2
iRow = Go_Grid.Rows.Count 'MiDato1

If iCol = 0 Then
MsgBox("No hay información por exportar a Excel", MsgBoxStyle.Information, GsTituloMsg)
Else
'Aqui recorremos todas las filas
For i As Integer = 1 To iCol
If Go_Grid.Columns(i - 1).Visible = True Then
exHoja.Cells.Item(1, i) = Go_Grid.Columns(i - 1).Name.ToString
exHoja.Cells.Item(1, i).HorizontalAlignment = 3
End If
Next
'Por cada fila pone todas las columnas y vamos escribiendo.
For Fila As Integer = 0 To iRow - 1
For Col As Integer = 0 To iCol - 1
If Go_Grid.Columns(Col).Visible = True Then
exHoja.Cells.Item(1, Col + 1) = Go_Grid.Columns(Col).HeaderText 'Estas son las columnas del encabezado
exHoja.Cells.Item(Fila + 2, Col + 1) = Go_Grid.Rows(Fila).Cells(Col).Value
End If
Next
Next

'Titulo en negrita, Alineado al centro y que el tamaño de la columna se ajuste al texto
exHoja.Rows.Item(1).Font.Bold = 1
exHoja.Rows.Item(1).HorizontalAlignment = 3
exHoja.Columns.AutoFit()

'Aplicación visible
exApp.Application.Visible = True
End If

'Se eliminan las variables de objeto excel
exApp = Nothing
exHoja = Nothing
exLibro = Nothing

Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Information, "Error al exportar a Excel")
Return False

End Try

Return True

End Function

Espero te sirva, saludos.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Ayuda para exportar datos de datagrid a excel

Publicado por Veronica (28 intervenciones) el 11/11/2009 02:58:56
Hola a todos:
Desde ya MUCHAS GRACIAS a quienes me han dado una mano enorme con estos códigos para poder exportar a Excel el contenido de un datagridview.

Una duda más; desde q utilicé el código, empecé a tener problemas con el filtrado de datos en el datagridview.
Por ejemplo, cuando coloco la referencia Mocrosoft.Office.Interop.Excel automáticamente me señala en azul el criterio de filtrado dicciendome q son demasiado argumentos para la instrucción Select. Y si por caso se me ocurre quitar la referencia, ese error no lo tengo pero no me deja filtrar tampoco.

¿Alguien tiene idea q puede ser?....antes no sucedía esto y la verdad q me cansé de darle vueltas.

Este es el código q utilizo para el filtrado:

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Dim mitabla As DataTable = Me.ContactosDataSet.Contactos
Dim filas() As DataRow

filas = mitabla.Select("Apellido LIKE '" & TextBox1.Text & "%'")

If filas.Length > 0 Then
dtgContactos.DataSource = filas
dtgContactos.Refresh()
Me.ContactosDataSet.Clear()
End If
End Sub
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Ayuda para exportar datos de datagrid a excel

Publicado por Nelly (1 intervención) el 24/12/2009 18:13:56
A mi el filtro en una tabla me sale de esta manera es cosa de que adaptes tu codigo....

Public Sub Buscar(ByVal nomObra As String, ByVal Folio As String, ByVal Equipo As String, ByVal Personal As String)
Sqlconnection1 = New SqlConnection(conexion)
cmd = New SqlCommand
cmd.CommandText = "SELECT * FROM Obra "
cmd.Connection = Sqlconnection1
Sqlconnection1.Open()
cmd.ExecuteNonQuery()
Sqlconnection1.Close()
da = New SqlDataAdapter(cmd)
ds = New DataSet()
da.Fill(ds)
vista = ds.Tables(0).DefaultView
DataGridView1.DataSource = vista
vista.RowFilter = "nomObra LIKE '%" & nomObra & "%'"
End Sub
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Ayuda para exportar datos de datagrid a excel

Publicado por Helmut Tijerino (1 intervención) el 08/03/2013 17:20:31
Function GridAExcel(ByVal DtgdV As DataGridView) As Boolean

'Creamos las variables
Dim exApp As New Excel.Application
Dim exLibro As Excel.Workbook
Dim exHoja As Excel.Worksheet

Try

'Añadimos el Libro al programa, y la hoja al libro
exLibro = exApp.Workbooks.Add
exHoja = exLibro.Worksheets.Add()

' Variables para # de columnas y # de renglones
Dim NCol As Integer = Me.DtgdV.ColumnCount
Dim NRow As Integer = Me.DtgdV.RowCount

'Aqui recorremos todas las filas
For i As Integer = 1 To NCol

exHoja.Cells.Item(1, i) = Me.DtgdV.Columns(i - 1).Name.ToString
exHoja.Cells.Item(1, i).HorizontalAlignment = 3

Next

For Filas As Integer = 0 To NRow - 1

For Col As Integer = 0 To NCol - 1

exHoja.Cells.Item(Filas + 2, Col + 1) = Me.DtgdV.Rows(Filas).Cells(Col).Value
Next

Next

'Titulo en negrita, Alineado al centro y que el tamaño de la columna se ajuste al texto
exHoja.Rows.Item(1).Font.Bold = 1
exHoja.Rows.Item(1).HorizontalAlignment = 3
exHoja.Columns.AutoFit()

'Se carga la aplicacion
exApp.Application.Visible = True

'Se liberan los objetos instanciados de la memoria
exApp = Nothing
exHoja = Nothing
exLibro = Nothing

Catch ex As Exception

MessageBox.Show(ex.Message)

Return False

End Try

Return True


End Function
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Ayuda para exportar datos de datagrid a excel

Publicado por Hiram (1 intervención) el 20/04/2015 18:06:56
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
' CODIGO DE VB NET
' REFERENCIA EN EL PROYECTO (Microsoft Excel 12.0 Object Library)
' BUSCARLA EN PESTAÑA COM   (C:\Program Files (x86)\Microsoft Office\Office12\EXCEL>EXE)
 
 
 
Imports Excel = Microsoft.Office.Interop.Excel
Imports Microsoft.Vbe.Interop
 
Public Class Form1
 
Sub DATAGRIDVIEW_TO_EXCEL(ByVal DGV As DataGridView)
        Try
            Dim DTB = New DataTable, RWS As Integer, CLS As Integer
 
            For CLS = 0 To DGV.ColumnCount - 1
                DTB.Columns.Add(DGV.Columns(CLS).Name.ToString)
            Next
 
            Dim DRW As DataRow
 
            For RWS = 0 To DGV.Rows.Count - 1
                DRW = DTB.NewRow
 
                For CLS = 0 To DGV.ColumnCount - 1
                    If DGV.Columns(CLS).Visible = True Then
                        Try
                            DRW(DTB.Columns(CLS).ColumnName.ToString) = DGV.Rows(RWS).Cells(CLS).Value.ToString
                        Catch ex As Exception
 
                        End Try
                    End If
                Next
 
                DTB.Rows.Add(DRW)
            Next
 
            DTB.AcceptChanges()
 
            Dim DST As New DataSet
            DST.Tables.Add(DTB)
            DTB.WriteXml("C:\MMS FILES\RESOURCES\XML.xml") ' SE CREA UN XML CON LA INFO DEL DATAGRIDVIEW
            MACRO("C:\MMS FILES\RESOURCES\XML.xml")        ' Y ESTE PROCEDIMIENTO LO ABRE EN EXCEL
 
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
 
    End Sub
 
    Private Sub MACRO(ByVal FLE As String)
        Try
            Dim xlApp As Object = New Microsoft.Office.Interop.Excel.Application
 
            Try ' OPCIONALMENTE LE DAS TAMAÑO A TU APLICACION DE EXCEL
                xlApp.Left = 250
                xlApp.Top = 100
                xlApp.Width = 900
                xlApp.Height = 550
            Catch ex As Exception
                ' PROTEGIENDO EL PROCESO SI LA ULTIMA APLICACION FUE EN FULL SCREEN
            End Try
 
            Dim xlWb As Excel.Workbook = xlApp.Workbooks.Add ' AGREGAS TU LIBRO DE EXCEL
 
            Dim MT As Integer ' Y OPCIONALMENTE LE DAS ESTILO Y FORMATO A SUS 3 HOJAS
 
            For MT = 3 To 1 Step -1
                xlWb.Sheets(MT).Select()
                xlWb.Sheets(MT).cells.select()
                xlWb.Sheets(MT).cells.Font.Name = "Arial"
                xlWb.Sheets(MT).cells.Font.Size = 8
                xlWb.Sheets(MT).cells.Font.bold = True
                xlWb.Sheets(MT).Range("A1").Select()
            Next
 
            ' LE CREAS UN MODULO LO NOMBRAS Y LE AGREGAS UNA MACRO DE ARRANQUE AL ABRIR
 
            Dim xlMod As Microsoft.Vbe.Interop.VBComponent = xlWb.VBProject.VBComponents.Add(Microsoft.Vbe.Interop.vbext_ComponentType.vbext_ct_StdModule)
            xlMod.Name = "Module1"
 
            Dim macroCode As String = _
            "Public Sub Main()" & vbCrLf & _
            "  ActiveWorkbook.XmlImport URL:=" & Chr(34) & FLE & Chr(34) & ", ImportMap:=Nothing, Overwrite:=True, Destination:=Range(" & Chr(34) & "$A$1" & Chr(34) & ")" & vbCrLf & _
            "  ActiveSheet.ListObjects(" & Chr(34) & "Table1" & Chr(34) & ").TableStyle = " & Chr(34) & "TableStyleMedium12" & vbCrLf & _
            "  Sheet1.Range(" & Chr(34) & "A2" & Chr(34) & ").Select" & vbCrLf & _
            "  ActiveWindow.FreezePanes = True" & vbCrLf & _
            "End Sub"
 
            xlMod.CodeModule.AddFromString(macroCode)
 
            xlApp.Visible = True
            xlApp.Application.Run("Main")
 
            ' OPCIONALMENTE (RECOMENDADO DIRIA YO) BORRAS TU MODULO SALVO QUE QUIERAS VERLO DURANTE LAS PRUEBAS
 
            Dim MDL As Object = xlApp.Application.VBE.ActiveVBProject.VBComponents
            MDL.Remove(VBComponent:=MDL.Item("Module1"))
 
            ' Y CIERRAS ESTE PROCEDIMIENTO LIBERANDO LAS VARIABLES
 
            ReleaseObject(xlApp)
            ReleaseObject(xlMod)
            ReleaseObject(xlWb)
            ReleaseObject(MDL)
 
        Catch ex As Exception
            MsgBox(ex.ToString())
        End Try
 
    End Sub
 
    Private Sub ReleaseObject(ByVal OBJ As Object)
        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(OBJ)
        Catch ex As Exception
 
        End Try
 
        OBJ = Nothing
        GC.Collect()
    End Sub
 
End Class
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar