Grid a Excel

2
Public Function GridAExcel( ByVal DGV As DataGridView ) As Boolean 'Creamos las variables Dim exApp As New Microsoft.Office.Interop.Excel.Application Dim exLibro As Microsoft.Office.Interop.Excel.Workbook Dim exHoja As Microsoft.Office.Interop.Excel.Worksheet Try exLibro = exApp.Workbooks.Add exHoja = exLibro.Worksheets.Add() ' ¿Cuantas columnas y cuantas filas? Dim NCol As Integer = DGV .ColumnCount Dim NRow As Integer = DGV .RowCount 'recorremos todas las filas, y por cada fila todas las columnas 'y vamos escribiendo. For i As Integer = 1 To NCol exHoja.Cells.Item(1, i)= DGV .Columns(i-1).Name.ToString Next For Fila As Integer = 0 To NRow - 1 For Col As Integer = 0 To NCol - 1 exHoja.Cells.Item(Fila+2, Col+1)= DGV .Rows(Fila).Cells(Col).Value() Next Next 'Titulo en negrita, Alineado exHoja.Rows.Item(1).Font.Bold = 1 exHoja.Rows.Item(1).HorizontalAlignment = 3 exHoja.Columns.AutoFit() 'para visualizar el libro exApp.Application.Visible = True exHoja = Nothing exLibro = Nothing exApp = Nothing Catch ex As Exception MsgBox(ex.Message, MsgBoxStyle.Critical, "Error al exportar a Excel" )

Transcript of Grid a Excel

Page 1: Grid a Excel

Public Function GridAExcel(ByVal DGV As DataGridView) As Boolean

        'Creamos las variables

        Dim exApp As New Microsoft.Office.Interop.Excel.Application        Dim exLibro As Microsoft.Office.Interop.Excel.Workbook        Dim exHoja As Microsoft.Office.Interop.Excel.Worksheet

        Try

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

    ' ¿Cuantas columnas y cuantas filas?            Dim NCol As Integer = DGV.ColumnCount            Dim NRow As Integer = DGV.RowCount    'recorremos todas las filas, y por cada fila todas las columnas    'y vamos escribiendo.          For i As Integer = 1 To NCol            exHoja.Cells.Item(1, i)=DGV.Columns(i-1).Name.ToString          Next

          For Fila As Integer = 0 To NRow - 1              For Col As Integer = 0 To NCol - 1                exHoja.Cells.Item(Fila+2, Col+1)=                DGV.Rows(Fila).Cells(Col).Value()              Next

           Next 'Titulo en negrita, Alineado            exHoja.Rows.Item(1).Font.Bold = 1            exHoja.Rows.Item(1).HorizontalAlignment = 3            exHoja.Columns.AutoFit()'para visualizar el libro            exApp.Application.Visible = True            exHoja = Nothing            exLibro = Nothing            exApp = Nothing 

Catch ex As ExceptionMsgBox(ex.Message, MsgBoxStyle.Critical, "Error al exportar a Excel")

    Return FalseEnd TryReturn TrueEnd Function

Page 2: Grid a Excel