Inicio > BASE DATOS > EXPORTAR DATAGRIDVIEW A EXCEL

EXPORTAR DATAGRIDVIEW A EXCEL

Hoy Aprenderemos como exportar un datagridview a excel 2007, lo primero que tenemos que hacer es crear un formulario similar :

En evento Load del formulario colocamos el siguiente codigo:

Try
            'Intentar conectar a la DB.
            con.Open()
            Dim cmd As New SqlCommand("Select * from products", con)
            Dim drd As SqlDataReader = cmd.ExecuteReader(CommandBehavior.SingleResult)
            Dim bs As New BindingSource
            bs.DataSource = drd
            DataGridView1.DataSource = bs
            drd.Close()
            con.Close()
        Catch ex As Exception
            'Si el intento es fallido, mostrar MsgBox y cerramos la aplicacion.
            MessageBox.Show("No se pudo conectar con la DB.", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Me.Close()
        End Try

creamos una funcion exportardatosexcel para luego llamarla desde el boton excel

Public Sub ExportarDatosExcel(ByVal DataGridView1 As DataGridView, ByVal titulo As String)
        Dim m_Excel As New Excel.Application
        Dim col, fil As Integer
        col = dgvProducto.Columns.Count + 8
        fil = dgvProducto.Rows.Count + 8
        m_Excel.Cursor = Excel.XlMousePointer.xlWait
        m_Excel.Visible = True
        Dim objLibroExcel As Excel.Workbook = m_Excel.Workbooks.Add
        Dim objHojaExcel As Excel.Worksheet = objLibroExcel.Worksheets(1)
        With objHojaExcel
            .Visible = Excel.XlSheetVisibility.xlSheetVisible
            .Activate()
            'Encabezado.
            .Range("A1:L1").Merge()
            .Range("A1:L1").Value = "ITEC"
            .Range("A1:L1").Font.Bold = True
            .Range("A1:L1").Font.Size = 16
            'Texto despues del encabezado.
            .Range("A2:L2").Merge()
            .Range("A2:L2").Value = titulo
            .Range("A2:L2").Font.Bold = True
            .Range("A2:L2").Font.Size = 10
            'Nombres
            'Estilo a titulos de la tabla.
            .Range("A6:P6").Font.Bold = True
            'Establecer tipo de letra al rango determinado.
            .Range("A1:P37").Font.Name = "Tahoma"
            'Los datos se registran a partir de la columna A, fila 4.
            Const primeraLetra As Char = "A"
            Const primerNumero As Short = 6
            Dim Letra As Char, UltimaLetra As Char
            Dim Numero As Integer, UltimoNumero As Integer
            Dim cod_letra As Byte = Asc(primeraLetra) - 1
            Dim sepDec As String = Application.CurrentCulture.NumberFormat.NumberDecimalSeparator
            Dim sepMil As String = Application.CurrentCulture.NumberFormat.NumberGroupSeparator
            Dim strColumna As String = ""
            Dim LetraIzq As String = ""
            Dim cod_LetraIzq As Byte = Asc(primeraLetra) - 1
            Letra = primeraLetra
            Numero = primerNumero
            Dim objCelda As Excel.Range
            For Each c As DataGridViewColumn In DataGridView1.Columns
                If c.Visible Then
                    : If Letra = "Z" Then
                        Letra = primeraLetra
                        cod_letra = Asc(primeraLetra)
                        cod_LetraIzq += 1
                        LetraIzq = Chr(cod_LetraIzq)
                    Else
                        cod_letra += 1
                        Letra = Chr(cod_letra)
                    End If
                    strColumna = LetraIzq + Letra + Numero.ToString
                    objCelda = .Range(strColumna, Type.Missing)
                    objCelda.Value = c.HeaderText
                    objCelda.EntireColumn.Font.Size = 10
                    'Establece un formato a los numeros por Default.
                    'objCelda.EntireColumn.NumberFormat = c.DefaultCellStyle.Format
                    If c.ValueType Is GetType(Decimal) OrElse c.ValueType Is GetType(Double) Then
                        objCelda.EntireColumn.NumberFormat = "#" + sepMil + "0" + sepDec + "00"
                    End If
                End If
            Next
            Dim objRangoEncab As Excel.Range = .Range(primeraLetra + Numero.ToString, LetraIzq + Letra + Numero.ToString)
            objRangoEncab.BorderAround(1, Excel.XlBorderWeight.xlMedium)
            UltimaLetra = Letra
            Dim UltimaLetraIzq As String = LetraIzq
            'Cargar Datos del DataGridView.
            Dim i As Integer = Numero + 1
            For Each reg As DataGridViewRow In DataGridView1.Rows
                LetraIzq = ""
                cod_LetraIzq = Asc(primeraLetra) - 1
                Letra = primeraLetra
                cod_letra = Asc(primeraLetra) - 1
                For Each c As DataGridViewColumn In DataGridView1.Columns
                    If c.Visible Then
                        If Letra = "Z" Then
                            Letra = primeraLetra
                            cod_letra = Asc(primeraLetra)
                            cod_LetraIzq += 1
                            LetraIzq = Chr(cod_LetraIzq)
                        Else
                            cod_letra += 1
                            Letra = Chr(cod_letra)
                        End If
                        strColumna = LetraIzq + Letra
                        'Aqui se realiza la carga de datos.
                        .Cells(i, strColumna) = IIf(IsDBNull(reg.ToString), "", reg.Cells(c.Index).Value)
                        'Establece las propiedades de los datos del DataGridView por Default.
                        '.Cells(i, strColumna) = IIf(IsDBNull(reg.(c.DataPropertyName)), c.DefaultCellStyle.NullValue, reg(c.DataPropertyName))
                        '.Range(strColumna + i, strColumna + i).In()
                    End If
                Next
                Dim objRangoReg As Excel.Range = .Range(primeraLetra + i.ToString, strColumna + i.ToString)
                objRangoReg.Rows.BorderAround()
                objRangoReg.Select()
                i += 1
            Next
            UltimoNumero = i
            'Dibujar las líneas de las columnas.
            LetraIzq = ""
            cod_LetraIzq = Asc("A")
            cod_letra = Asc(primeraLetra)
            Letra = primeraLetra
            For Each c As DataGridViewColumn In DataGridView1.Columns
                If c.Visible Then
                    objCelda = .Range(LetraIzq + Letra + primerNumero.ToString, LetraIzq + Letra + (UltimoNumero - 1).ToString)
                    objCelda.BorderAround()
                    If Letra = "Z" Then
                        Letra = primeraLetra
                        cod_letra = Asc(primeraLetra)
                        LetraIzq = Chr(cod_LetraIzq)
                        cod_LetraIzq += 1
                    Else
                        cod_letra += 1
                        Letra = Chr(cod_letra)
                    End If
                End If
            Next
            'Dibujar el border exterior grueso de la tabla.
            Dim objRango As Excel.Range = .Range(primeraLetra + primerNumero.ToString, UltimaLetraIzq + UltimaLetra + (UltimoNumero - 1).ToString)
            objRango.Select()
            objRango.Columns.AutoFit()
            objRango.Columns.BorderAround(1, Excel.XlBorderWeight.xlMedium)
        End With
        m_Excel.Cursor = Excel.XlMousePointer.xlDefault

    End Sub

Al final en el boton exportar llamamos a la funcion que hemos creado

Try
'Intentar generar el documento.
'Se adjunta un texto debajo del encabezado
ExportarDatosExcel(DataGridView1, "Reporte de PRODUCTOS ")
Catch ex As Exception
'Si el intento es fallido, mostrar MsgBox.
MessageBox.Show("No se puede generar el documento Excel.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

Aqui les adjunto el codigo

Categorías: BASE DATOS
  1. Guilver
    May 9, 2011 a las 5:53 pm

    Excelente codigo muy claro y funcional.
    GRacias.

  2. jaz
    noviembre 15, 2011 a las 5:47 pm

    y si quieres exportarlo a varios libros, es decir en el cuadro tienes info de clientes de un pais y quieres que se guarde por cada distrito en un libro de exel distinto. como se podria hacer eso ?’

  3. Juan Cruz Blas
    marzo 25, 2012 a las 10:44 pm

    la verdad es una gran ayuda esta información, EN VERDAD MUCHAS GRACIAS

  4. Sergio Tincopa
    May 11, 2012 a las 9:52 pm

    Excelente ayuda!! Muchas gracias

  5. Felipe Alejandro Tapia Polanco
    julio 31, 2012 a las 4:08 am

    te hago una consulta el exportado me funciona muy bn para todo datos pero no me exporta los datos time de la base de datos mysql y no me los genera al exportarlos a excel nose como se puede hacer?

  6. julio 31, 2012 a las 9:52 pm

    Uff muchas gracias por la Info! me saco de un problemon!

  7. Anónimo
    noviembre 16, 2012 a las 3:42 pm

    De lo mejor hasta ahora

  8. abril 20, 2015 a las 4:11 pm

    ‘ 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

  1. No trackbacks yet.

Deja un comentario