然后导入命名空间:
Imports Microsoft.Office.Interop
Imports System.Data.SqlClient
最后建立一个ImportToExcel的函数,函数代码如下:
'''
''' 将Datagridview中的数据导出至Excel中
'''
''' Datagridview类型
''' 布尔值类型,导出是否成功
'''
Public Function ImportToExcel(ByVal DGV As DataGridView) As Boolean
'不允许导出空数据
If DGV.RowCount = 0 Then
MsgBox("记录为空,请重新查询!", vbOKOnly + vbInformation, "系统提示")
Else
'创建Excel
Dim bln As Boolean
Dim xlApp, xlBook, xlSheet As Object
xlApp = CreateObject("Excel.Application")
xlBook = xlApp.Workbooks.Add
xlSheet = xlBook.Worksheets(1)
'打开Sheet1
Dim rowindex, colindex As Integer
rowindex = 1 '行
colindex = 0 '列
xlSheet = xlApp.Worksheets("sheet1") '打开Sheet1那一页
'将Datagridview的数据添加到DataTable中
Dim table As New DataTable
table = DGV.DataSource 'Datagridview数据源
Dim row As DataRow '定义Row为表格的行
Dim col As DataColumn '定义col为表格的列