首先添加一个模块ImportToExcel,并添加引用
然后导入命名空间:
Imports Microsoft.Office.Interop
Imports System.Data.SqlClient
最后建立一个ImportToExcel的函数,函数代码如下:
''' <summary>
''' 将Datagridview中的数据导出至Excel中
''' </summary>
''' <param name="DGV">Datagridview类型</param>
''' <returns>布尔值类型,导出是否成功</returns>
''' <remarks></remarks>
Public Function ImportToExcel(ByVal DGV As DataGridView) As Boolean '创建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为表格的列 '将Datagridview中的每一列写入Excel中
For Each col In table.Columns
colindex = colindex + 1
xlApp.Cells(1, colindex) = col.ColumnName
Next '将Datagridview中的每一行写入Excel中
For Each row In table.Rows
rowindex = rowindex + 1
colindex = 0
For Each col In table.Columns
colindex = colindex + 1
xlApp.Cells(rowindex, colindex) = row(col.ColumnName)
Next
Next
xlApp.Visible = True Return bln End Function
调用方法
Private Sub btnExportExcel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExportExcel.Click '不允许导出空数据
If DataGridView1.DataSource = "" Then
MsgBox("记录为空,请重新查询!", vbOKOnly + vbInformation, "系统提示")
txtCardID.Clear()
txtCardID.Focus()
Else
Call ImportToExcel.ImportToExcel(DataGridView1)
End If End Sub
实现效果如下: