Foros del Web » Programación para mayores de 30 ;) » .NET »

Exportar a Excel contenido de DataGridView con los HeaderText

Estas en el tema de Exportar a Excel contenido de DataGridView con los HeaderText en el foro de .NET en Foros del Web. Buenos dias compañeros, estoy exportando a excel el contenido de un datagridview a un excel utilizando el siguiente procedimiento: Código: 'EXPORTAR A EXCEL CONTENIDO DATAGRIDVIEW ...
  #1 (permalink)  
Antiguo 20/03/2009, 09:45
Avatar de Carlojas  
Fecha de Ingreso: junio-2007
Ubicación: Shikasta
Mensajes: 1.272
Antigüedad: 16 años, 10 meses
Puntos: 49
Exportar a Excel contenido de DataGridView con los HeaderText

Buenos dias compañeros, estoy exportando a excel el contenido de un datagridview a un excel utilizando el siguiente procedimiento:
Código:
'EXPORTAR A EXCEL CONTENIDO DATAGRIDVIEW
    Public Sub ExportarExcel(ByVal Dg As DataGridView, ByVal Ruta As String)
        On Error Resume Next
        Dim xlApp As Excel.Application
        Dim xlWorkBook As Excel.Workbook
        Dim xlWorkSheet As Excel.Worksheet
        Dim misValue As Object = System.Reflection.Missing.Value
        Dim i As Integer
        Dim j As Integer
        xlApp = New Excel.ApplicationClass
        xlWorkBook = xlApp.Workbooks.Add(misValue)
        xlWorkSheet = xlWorkBook.Sheets(1)

        For i = 0 To Dg.RowCount - 2
            For j = 0 To Dg.ColumnCount - 1
                xlWorkSheet.Cells(i + 1, j + 1) = Dg(j, i).Value.ToString()
            Next
        Next

        If Ruta <> vbNullString Then
            xlWorkSheet.SaveAs(Ruta)
            xlWorkBook.Close()
            xlApp.Quit()
            releaseObject(xlApp)
            releaseObject(xlWorkBook)
            releaseObject(xlWorkSheet)
            MessageBox.Show("El Archivo fue exportado satisfactoriamente " + Ruta, "Exportación de Archivos", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Process.Start(Ruta)
        Else
            MessageBox.Show("Debe seleccionar la ubicación donde guardar el archivo", "Exportación de Archivos", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Sub
        End If
    End Sub

    'OBJETO DEL COMPONENTE COM
    Private Sub releaseObject(ByVal obj As Object)
        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
            obj = Nothing
        Catch ex As Exception
            obj = Nothing
        Finally
            GC.Collect()
        End Try
    End Sub
Eso hace el proceso sin ningún inconveniente, mi inquietud es como se haría para que tambien exportara los HeaderText de cada una de las columnas al excel.


Agradesco sus comentarios al respecto.

Saludos y Gracias.
__________________
"SELECT * FROM Mujeres WHERE situacion NOT IN ('CASADAS','CON HIJOS','ATORMENTADAS','CUASI-ENNOVIADAS') AND personalidad <> 'INTENSA'"
  #2 (permalink)  
Antiguo 20/03/2009, 12:47
Avatar de Carlojas  
Fecha de Ingreso: junio-2007
Ubicación: Shikasta
Mensajes: 1.272
Antigüedad: 16 años, 10 meses
Puntos: 49
Respuesta: Exportar a Excel contenido de DataGridView con los HeaderText

Listo compañeros al fin lo pude solucionar de esta forma, recorriendo el Datatable:

Código:
 'EXPORTAR A EXCEL CONTENIDO DATATABLE
    Public Sub ExportToExcel(ByVal Dt As DataTable, ByVal Path As String)
        Dim excelApplication As Excel.Application = New Excel.Application
        Dim excelWorkbook As Excel.Workbook = CType(excelApplication.Workbooks.Add(System.Reflection.Missing.Value), Excel.Workbook)
        Dim excelSheet As Excel.Worksheet = CType(excelWorkbook.Sheets(1), Excel.Worksheet)

        For i As Integer = 0 To Dt.Columns.Count - 1
            CType(excelSheet.Cells(1, i + 1), Excel.Range).Value2 = Dt.Columns(i).ColumnName
        Next i

        excelSheet.Range(excelSheet.Cells(1, 1), excelSheet.Cells(1, Dt.Columns.Count)).Font.Bold = True
        excelSheet.Range(excelSheet.Cells(1, 1), excelSheet.Cells(1, Dt.Columns.Count)).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
        For i As Integer = 0 To Dt.Rows.Count - 1
            excelSheet.Cells.Range(excelSheet.Cells(i + 2, 1), excelSheet.Cells(i + 2, Dt.Columns.Count)).Value2 = Dt.Rows(i).ItemArray
        Next i

        Dim tmp As String
        tmp = excelSheet.Cells.Range(excelSheet.Cells(2, 1), excelSheet.Cells(2, 1)).Value2.ToString()
        If Path <> vbNullString Then
            excelWorkbook.Close(True, Path, Nothing)

            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorkbook)
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApplication)
            excelWorkbook = Nothing
            excelApplication = Nothing

            MessageBox.Show("El Archivo fue exportado satisfactoriamente " + Path, "Exportación de Archivos", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Process.Start(Path)
        Else
            MessageBox.Show("Debe seleccionar la ubicación donde guardar el archivo", "Exportación de Archivos", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Sub
        End If
    End Sub

Saludos y Gracias por todo.
__________________
"SELECT * FROM Mujeres WHERE situacion NOT IN ('CASADAS','CON HIJOS','ATORMENTADAS','CUASI-ENNOVIADAS') AND personalidad <> 'INTENSA'"
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 08:07.