Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,


How To export DataGridview Value to Excel in VB.NET 2.0 Windows Form
Posted

Hi,

VB
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
 
Share this answer
 
v2
Comments
mitchiee1226 8-Jul-14 4:35am    
How do you put the Title of the columns in this code?
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900