01.
Imports
System.Data
02.
Imports
System.Data.OleDb
03.
Imports
System.IO
04.
Imports
System.Data.SqlClient
05.
Imports
Excel = Microsoft.Office.Interop.Excel
06.
07.
08.
Private
Sub
Button1_Click(
ByVal
sender
As
System.
Object
,
ByVal
e
As
System.EventArgs)
Handles
Button1.Click
09.
Dim
xlApp
As
Excel.Application
10.
Dim
xlWorkBook
As
Excel.Workbook
11.
Dim
xlWorkSheet
As
Excel.Worksheet
12.
Dim
misValue
As
Object
= System.Reflection.Missing.Value
13.
Dim
i
As
Integer
14.
Dim
j
As
Integer
15.
16.
17.
xlApp =
New
Excel.Application
18.
xlWorkBook = xlApp.Workbooks.Add(misValue)
19.
xlWorkSheet = xlWorkBook.Sheets(
"sheet1"
)
20.
For
i = 0
To
DataGridView.RowCount - 2
21.
For
j = 0
To
DataGridView.ColumnCount - 1
22.
xlWorkSheet.Cells(i + 1, j + 1) = _
23.
DataGridView(j, i).Value.ToString()
24.
Next
25.
Next
26.
27.
Dim
ExcelName
As
String
28.
ExcelName = txtExcelName.Text
29.
30.
xlWorkSheet.SaveAs(
"D:\file vb excel\" & ExcelName & "
.xlsx")
31.
xlWorkBook.Close()
32.
xlApp.Quit()
33.
34.
releaseObject(xlApp)
35.
releaseObject(xlWorkBook)
36.
releaseObject(xlWorkSheet)
37.
38.
MsgBox(
"You can find the file D:\file vb excel\" & ExcelName & "
.xlsx")
39.
End
Sub
40.
41.
Private
Sub
releaseObject(
ByVal
obj
As
Object
)
42.
Try
43.
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
44.
obj =
Nothing
45.
Catch
ex
As
Exception
46.
obj =
Nothing
47.
Finally
48.
GC.Collect()
49.
End
Try
50.
End
Sub