The given example demonstrate how to export
data or records from DataGridView Control to Excel Spread Sheet. You will also
see how to open a specific folder and select a file by pressing a button in
vb.net.
Add reference to your
project : "Microsoft Excel 12.0 Object Library"
For more information about references please refer
the enclosed project(.zip).
Code :
Imports
System.Data.OleDb
Imports
Microsoft.Office.Interop
Public Class
Form1
Private Sub Form1_Load(ByVal
sender As System.Object,
ByVal e As
System.EventArgs)
Handles MyBase.Load
Dim Con As New
OLEDBConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=.\\employee.accdb")
Dim Dst =
New DataSet
Dim Dad =
New
OleDbDataAdapter("select * from
empinfo order by Id", Con)
Dad.Fill(Dst, "employee")
DataGridView1.DataSource = Dst.Tables(0)
End Sub
Private Sub Button3_Click(ByVal
sender As System.Object,
ByVal e As
System.EventArgs)
Handles Button3.Click
End
End Sub
Private Sub Button1_Click(ByVal
sender As System.Object,
ByVal e As
System.EventArgs)
Handles Button1.Click
Dim
App As Excel.Application
Dim WorkBook
As Excel.Workbook
Dim WorkSheet
As Excel.Worksheet
Dim
misValue As Object
= System.Reflection.Missing.Value
Dim i, j As Integer
Try
App =
New Excel.Application
WorkBook = App.Workbooks.Add(misValue)
WorkSheet = WorkBook.Sheets("Sheet1")
For i = 0
To DataGridView1.ColumnCount - 1
WorkSheet.Cells(1, i + 1) = DataGridView1.Columns(i).HeaderText
Next
For
i = 0 To DataGridView1.RowCount - 2
For j = 0
To DataGridView1.ColumnCount - 1
WorkSheet.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString()
Next
Next
WorkSheet.SaveAs("D:\exportedfile.xlsx")
WorkBook.Close()
App.Quit()
ReleaseObject(App)
ReleaseObject(WorkBook)
ReleaseObject(WorkSheet)
Catch ex As Exception
End Try
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
Private Sub Button2_Click(ByVal
sender As System.Object,
ByVal e As
System.EventArgs)
Handles Button2.Click
Process.Start("explorer",
"/select," &
"D:\exportedfile.xlsx")
End Sub
End Class
Output :
At the startup all records
will be shown in DataGridView Control

The following message (as
shown in figure) will appear if file already exist in the folder specified

By clicking on the "open
location" button, you can find the excel file.

The generated excel file will
show the records as shown in figure below
