Export datagridview to Excel

1

-I get this error when opening the datagrid export to excel, will a library be necessary to correct this error?

I need to export a datagrid that brings me a Select query with 251 rows to Excel, I have a code to do it but it happens that when there are many rows, the program stops:

Public Function GridAExcel(ByVal ElGrid 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
            ''Añadimos el Libro al programa, y la hoja al libro
            exLibro = exApp.Workbooks.Add
            exHoja = exLibro.Worksheets.Add
            '' ¿Cuantas columnas y cuantas filas?
            Dim NCol As Integer = ElGrid.ColumnCount
            Dim NRow As Integer = ElGrid.RowCount
            ''Aqui 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) = ElGrid.Columns(i - 1).Name.ToString 
End Function

This is the error that comes to me, I do not know what the truth may be, I already import the library in the form and in the class.

    
asked by Jose Emiliano Paz 07.04.2016 в 21:21
source

4 answers

2

It's easy, you just have to leave the format that is going to save the code that should be in * .xlsx format.

I sent you the code I use.

'Exportar Data Grid de 1 a 3 dias
Private Sub btnImprimirde1a3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImprimirde1a3.Click
    Try
        If ((dgv1a3.Columns.Count = 0) Or (dgv1a3.Rows.Count = 0)) Then
            Exit Sub
        End If

        'Creando Dataset para Exportar
        Dim dset As New DataSet
        'Agregar tabla al Dataset
        dset.Tables.Add()
        'AGregar Columna a la tabla
        For i As Integer = 0 To dgv1a3.ColumnCount - 1
            dset.Tables(0).Columns.Add(dgv1a3.Columns(i).HeaderText)
        Next
        'Agregar filas a la tabla
        Dim dr1 As DataRow
        For i As Integer = 0 To dgv1a3.RowCount - 1
            dr1 = dset.Tables(0).NewRow
            For j As Integer = 0 To dgv1a3.Columns.Count - 1
                dr1(j) = dgv1a3.Rows(i).Cells(j).Value
            Next
            dset.Tables(0).Rows.Add(dr1)
        Next

        Dim aplicacion As New Microsoft.Office.Interop.Excel.ApplicationClass
        Dim wBook As Microsoft.Office.Interop.Excel.Workbook
        Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet

        wBook = aplicacion.Workbooks.Add()
        wSheet = wBook.ActiveSheet()

        Dim dt As System.Data.DataTable = dset.Tables(0)
        Dim dc As System.Data.DataColumn
        Dim dr As System.Data.DataRow
        Dim colIndex As Integer = 0
        Dim rowIndex As Integer = 0

        For Each dc In dt.Columns
            colIndex = colIndex + 1
            aplicacion.Cells(1, colIndex) = dc.ColumnName
        Next

        For Each dr In dt.Rows
            rowIndex = rowIndex + 1
            colIndex = 0
            For Each dc In dt.Columns
                colIndex = colIndex + 1
                aplicacion.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)

            Next
        Next
        'Configurar la orientacion de la  hoja y el tamaño
        wSheet.PageSetup.Orientation = Excel.XlPageOrientation.xlLandscape
        wSheet.PageSetup.PaperSize = Excel.XlPaperSize.xlPaperLegal
        'Configurar con negrilla la cabecera y tenga autofit
        wSheet.Rows.Item(1).Font.Bold = 1
        wSheet.Columns.AutoFit()


        Dim strFileName As String = "C:\Documents and Settings\All Users\Escritorio\Reporte de 1 a 3 dias.xlsx"
        Dim blnFileOpen As Boolean = False
        Try
            Dim fileTemp As System.IO.FileStream = System.IO.File.OpenWrite(strFileName)
            fileTemp.Close()
        Catch ex As Exception
            blnFileOpen = False
        End Try

        If System.IO.File.Exists(strFileName) Then
            System.IO.File.Delete(strFileName)
        End If
        MessageBox.Show("El documento fue exportado correctamente.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
        wBook.SaveAs(strFileName)
        aplicacion.Workbooks.Open(strFileName)
        aplicacion.Visible = True
    Catch ex As Exception
        MessageBox.Show(ex.Message, "SISTEMA INTEGRADO DE ADMINISTRACION DE PERSONAL", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub     
    
answered by 24.09.2018 в 20:12
0

I would recommend the same thing that I advise in this question

Como export a row from a DataGridView to a txt file

Do not export from a control but dump the data to a class and then use a library as being

filehelpers

Then you create a class

<DelimitedRecord(vbTab)> _
Public class Item

    Public Property Prop1 As String
    Public Property Prop2 As String
    Public Property Prop3 As String

End Class

and export by dumping the data into that class

Private Sub button2_Click(sender As Object, e As EventArgs)

    Dim Items As New List(Of Item)

    For Each row As DataGridViewRow In DataGridView1.Rows

        Dim _item As New Item() With { _
            .Prop1 = row.Cells(0).Value.ToString(), _
            .Prop2 = row.Cells(1).Value.ToString(), _
            .Prop3 = row.Cells(2).Value.ToString() _
        }

        Items.Add(_item)
    Next

    Dim engine = New FileHelperEngine(Of Item)
    engine.WriteFile("D:\Carpeta\Archivo.txt", Items.ToArray())

    MessageBox.Show("Datos Exportados correctamente")
End Sub

This way you do not export the grid directly to the file, but you use an intermediate class.

Remember to declare the Imports to System.Collections.Generic to recognize for example the method ToArray()

    
answered by 07.04.2016 в 21:38
0

Try it with the following code:

   Microsoft.Office.Interop.Excel.Application XcelApp = new Microsoft.Office.Interop.Excel.Application();
                XcelApp.Application.Workbooks.Add(Type.Missing);

                for (int i = 1; i < this.DataGridview.Columns.Count + 1; i++)
                {
                    XcelApp.Cells[1, i] = this.DataGridview.Columns[i - 1].HeaderText;
                }


                for (int i = 0; i < this.DataGridview.Rows.Count; i++)
                {
                    for (int j = 0; j < this.DataGridview.Columns.Count; j++)
                    {
                        XcelApp.Cells[i + 2, j + 1] = (this.DataGridview.Rows[i].Cells[j].Value != null) ? this.DataGridview.Rows[i].Cells[j].Value.ToString() : String.Empty;
                    }
                }
                XcelApp.Columns.AutoFit();
                XcelApp.Visible = true;

Only change the reference to your Grid;)

Good luck! : D

    
answered by 20.05.2016 в 18:35
0

I propose a solution that worked for me and quite a lot since I needed to export more than 20,000 records to an Excel and I wanted to prioritize how you say the speed.

Use the EPPlus library, which allows you to work with Excel.

What we need is to load the data that we are going to export to a DataTable in memory. Then we open a code and easily fill it with a single sentence.

  • We downloaded the EPPlus library: link

  • We add it to the reference of our project:

  • We create the code (in my case create a DataTable in Memory and I loaded it).

        Dim DataTablePrueba As New DataTable
        DataTablePrueba.Columns.Add("N1")
        DataTablePrueba.Columns.Add("N2")
        For x = 0 To 30000
            DataTablePrueba.Rows.Add(x, x)
        Next
        Dim fileg As New FileInfo("C:\exportacion\export.xlsx")
        Using package As New ExcelPackage(fileg)
            Dim ws As ExcelWorksheet = package.Workbook.Worksheets.Add("Hoja1")
            ws.Cells("A1").LoadFromDataTable(DataTablePrueba, True)
            package.Save()
        End Using
    
  • And if we take into account that the output directory that we created exists, we should already have the excel:
  •     
    answered by 19.08.2016 в 20:03