How to Export Data from DataGridView to Excel using VB.NET

Here is a tutorial on how to Export data from DataGridView to Excel using VB.NET.

DataGridView to Excel

Steps to Export Data from DataGridView to Excel:

1. Create a windows form application in VB.NET 2012 or 2010 or in 2008.2. Create a Button Titled Export. ( I assume you already have a DataGridView in your Project)

3. Add the Reference Microsoft.Office.Interop.Excel

4. Now add the following code to Export button on the event of Button click.

 vb.net |  copy code |? 
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim xlApp As Microsoft.Office.Interop.Excel.Application Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet Dim misValue As Object = System.Reflection.Missing.Value Dim i As Integer Dim j As Integer xlApp = New Microsoft.Office.Interop.Excel.Application xlWorkBook = xlApp.Workbooks.Add(misValue) xlWorkSheet = xlWorkBook.Sheets("sheet1") For i = 0 To DataGridView1.RowCount - 1 For j = 0 To DataGridView1.ColumnCount - 1 For k As Integer = 1 To DataGridView1.Columns.Count xlWorkSheet.Cells(1, k) = DataGridView1.Columns(k - 1).HeaderText xlWorkSheet.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString() Next Next Next xlWorkSheet.SaveAs("D:\vbexcel.xlsx") xlWorkBook.Close() xlApp.Quit() releaseObject(xlApp) releaseObject(xlWorkBook) releaseObject(xlWorkSheet) Dim res As MsgBoxResult res = MsgBox("Process completed, Would you like to open file?", MsgBoxStyle.YesNo) If (res = MsgBoxResult.Yes) Then Process.Start("d:\vbexcel.xlsx") End If End Sub

5. Now add this

 vb.net |  copy code |? 
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

6. Now run the application and click on Export Button, That’s it now you Export data from DataGridView to Excel Sheet.

Please See the following Screen Cast

Mobile Readers Click here for Video

About the author

I am a Computer lover, I love Technology, and I love to share my knowledge to the world.