Click here to Skip to main content
12,762,900 members (36,651 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: VB VB.NET
Hi,


How To export DataGridview Value to Excel in VB.NET 2.0 Windows Form
Posted 13-Jan-12 1:54am
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Hi,

 Private Sub btn_excel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_excel.Click
        'Export DataGridView to Excel
        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.Application
        xlworkbook = xlapp.Workbooks.Add(misvalue)
        xlworksheet = xlworkbook.Sheets("Sheet1")
        For i = 0 To gv.RowCount - 2
            For j = 0 To gv.ColumnCount - 1
                xlworksheet.Cells(i + 1, j + 1) = _
                    gv(j, i).Value.ToString()
            Next
        Next
        Dim dialog As New SaveFileDialog
        Dim result As DialogResult = dialog.ShowDialog
        Try
            xlworksheet.SaveAs(dialog.FileName)
        Catch exerr As Exception
        End Try

        xlworkbook.Close()
        xlapp.Quit()

        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
  Permalink  
v2
Comments
mitchiee1226 8-Jul-14 4:35am
   
How do you put the Title of the columns in this code?
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web01 | 2.8.170217.1 | Last Updated 30 Sep 2015
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100