Results 1 to 4 of 4

Thread: How to Export to Excel Using DataSource

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Oct 2010
    Posts
    76

    How to Export to Excel Using DataSource

    Hi experts,


    I'am having a problem in exporting my data from Datagridview to my Excel it takes to much time at it gives me an error that said it have to much rows (i'am exporting a Rows of 5000).

    How can i export my data using may datasource

    Here is my code in Retrievingmy Data from Database to Datagridview

    Code:
     Dim con As New SqlConnection(sqlcon)
            Try
                con.Open()
                Dim cmd As SqlCommand = con.CreateCommand
                cmd.CommandText = "usp_GetReports"
                cmd.CommandType = CommandType.StoredProcedure
                Dim dr As SqlDataReader = cmd.ExecuteReader
                Dim dt As New DataTable
                dt.Load(dr)
                DataGridViewReportV1.DataSource = dt
                cmd.ExecuteNonQuery()
            Catch ex As Exception
                MsgBox(ex.Message & vbNewLine & "Error in Retrieving")
            Finally
                If con IsNot Nothing Then
                    con.Close()
                    con.Dispose()
                End If
            End Try
    Here is how i'm exporting my data to excel
    Code:
     Dim xlApp As Excel.Application
            Dim xlWorkBook As Excel.Workbook
            Dim xlWorkSheet As Excel.Worksheet
            Dim misValue As Object = System.Reflection.Missing.Value
    
    
            xlApp = New Excel.ApplicationClass
            xlWorkBook = xlApp.Workbooks.Add(misValue)
            xlWorkSheet = xlWorkBook.Sheets("sheet1")
    
    
    
        // This is where i have an error if my rows are to large ///
            For i As Integer = 1 To DatagridReport.Columns.Count
                xlWorkSheet.Cells(1, i) = DatagridReport.Columns(i - 1).HeaderText
            Next
            For i As Integer = 0 To DatagridReport.Rows.Count - 2
                For j As Integer = 0 To DatagridReport.Columns.Count - 1
                    xlWorkSheet.Cells(i + 2, j + 1) = DatagridReport.Rows(i).Cells(j).Value.ToString()
                Next
            Next
     
            Dim sd As New SaveFileDialog 'declare save file dialog
    
            sd.Filter = "Excel File (*.xlsx)|*.xlsx"
            sd.Title = "Save an Excel File"
            sd.RestoreDirectory = True
    
            If sd.ShowDialog = Windows.Forms.DialogResult.OK Then 'check if save file dialog was close after selecting a path
                'MsgBox(sd.FileName)
                xlWorkSheet.SaveAs(sd.FileName) 'sd.filename reurns save file dialog path
                MsgBox("You can find the file " + sd.FileName)
                xlWorkBook.Close()
                xlApp.Quit()
            End If
    
    
            releaseObject(xlApp)
            releaseObject(xlWorkBook)
            releaseObject(xlWorkSheet)
        End Sub
        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
    Thank you for your guidance.

  2. #2
    Frenzied Member
    Join Date
    Nov 2010
    Posts
    1,470

    Re: How to Export to Excel Using DataSource

    why not export to csv and then import the csv

    its clunky but will work

  3. #3
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,109

    Re: How to Export to Excel Using DataSource

    I moved the thread to VB.NET, which is what the language is.

    I've never tried exporting that many records, but in this thread is a class I wrote for exporting records to Excel:

    http://www.vbforums.com/showthread.p...ter-base-class

    Frankly, it's kind of a pain. Since Excel works so well with CSVs, I tend to agree with incidentals. Alternatively, you might be able to write to Excel using ADO.NET with Excel being the 'database' in the operation. I've never tried this, but you can query either text files or spreadsheets, so it seems like you ought to be able to perform INSERT operations against a spreadsheet.
    My usual boring signature: Nothing

  4. #4
    PowerPoster
    Join Date
    Oct 2010
    Posts
    2,141

    Re: How to Export to Excel Using DataSource

    Since you are using Excel Interop, the last thing you want to do is to iterate each cell in a table. The ideal method is to create a 2D array of the values and set it to an equally sized 2D Excel range.

    I'm a bit confused as you show loading DataGridViewReportV1 from a Datatable, but in the export routine, you show using DatagridReport. I will assume that these two DGV's are the same.

    Since the data is already in a DataTable, I would export from that directly. The following is a simple example of exporting from a Datatable to an Excel spreadsheet using interop. Instead of creating one large array to export, it exports by row.
    VB.Net Code:
    1. Imports Microsoft.Office.Interop
    2. Public Class Form1
    3.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    4.         TestExport()
    5.     End Sub
    6.  
    7.     Private Sub TestExport()
    8.         Dim app As New Excel.Application
    9.         Dim wb As Excel.Workbook = app.Workbooks.Add
    10.         Dim ws As Excel.Worksheet = CType(wb.Worksheets.Item(1), Excel.Worksheet)
    11.         Dim dt As DataTable = New DemoDT
    12.         ExportDT(dt, ws.Range("b3"))
    13.         ' leave excel open
    14.         app.UserControl = True
    15.         app.Visible = True
    16.     End Sub
    17.  
    18.     Private Sub ExportDT(dt As DataTable, topLeftCell As Excel.Range)
    19.         Dim exportRange As Excel.Range = CType(topLeftCell.Cells.Item(1, 1), Excel.Range)
    20.         exportRange = exportRange.Resize(1, dt.Columns.Count)
    21.         ' create and export header
    22.         Dim header As New List(Of String)
    23.         For Each c As DataColumn In dt.Columns
    24.             header.Add(c.ColumnName)
    25.         Next
    26.         exportRange.Value2 = header.ToArray
    27.  
    28.         'export each row
    29.         For Each dr As DataRow In dt.Rows
    30.             exportRange = exportRange.Offset(1, 0)
    31.             exportRange.Value2 = dr.ItemArray
    32.         Next
    33.     End Sub
    34. End Class

    This code will work for any Datatable so long as the data types are compatible with Excel. For the purpose of the example, this is the DataTable used.
    VB.Net Code:
    1. Friend Class DemoDT : Inherits DataTable
    2.     Private Shared typString As Type = GetType(String), _
    3.                         typInt32 As Type = GetType(Int32), _
    4.                         typDateTime As Type = GetType(DateTime)
    5.  
    6.     Public Sub New()
    7.         MyBase.New()
    8.  
    9.         With Me.Columns
    10.             .Add("Name", typString)
    11.             .Add("Date", typDateTime)
    12.             .Add("Value", GetType(Single))
    13.         End With
    14.         With Me.Rows
    15.             .Add("Barney", New DateTime(1992, 3, 30), 10)
    16.             .Add("Betty", New DateTime(1998, 12, 11), 11)
    17.             .Add("Fred", New DateTime(1985, 2, 16), 12)
    18.             .Add("Wilma", New DateTime(1988, 5, 6), 32)
    19.         End With
    20.     End Sub
    21. End Class
    Last edited by TnTinMN; Apr 11th, 2016 at 10:10 AM. Reason: typos

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width