📅  最后修改于: 2023-12-03 15:25:13.352000             🧑  作者: Mango
在VB.NET 或 VBA 中,我们经常需要将 DataGridView 中的数据导出到Excel中进行数据分析。下面是一些常用的方法:
VB.NET 中提供了Microsoft.Office.Interop.Excel 库,可以用于操作 Excel 文件,实现将 DataGridView 导出到 Excel 的功能。下面是一个简单的示例代码:
Imports Microsoft.Office.Interop.Excel
' 将DataGridView导出到Excel
Private Sub ExportToExcel()
Dim excelApp As New Excel.Application
Dim excelBook As Excel.Workbook = excelApp.Workbooks.Add()
Dim excelSheet As Excel.Worksheet = CType(excelBook.Worksheets(1), Excel.Worksheet)
' 写入DataGridView的列标题
For j As Integer = 0 To DataGridView1.Columns.Count - 1
excelSheet.Cells(1, j + 1) = DataGridView1.Columns(j).HeaderText
Next
' 依次写入每行数据
For i As Integer = 0 To DataGridView1.Rows.Count - 1
For j As Integer = 0 To DataGridView1.Columns.Count - 1
excelSheet.Cells(i + 2, j + 1) = DataGridView1.Rows(i).Cells(j).Value.ToString()
Next
Next
'保存文件
excelBook.SaveAs("D:\ExcelFile.xlsx")
excelSheet = Nothing
excelBook = Nothing
excelApp.Quit()
excelApp = Nothing
End Sub
我们也可以通过 OleDB 的方式将 DataGridView 导出到 Excel。下面是一个简单的示例代码:
' 将DataGridView导出到Excel
Private Sub ExportToExcel()
Dim cn As New OleDbConnection With {.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=D:\ExcelFile.xlsx; Extended Properties='Excel 12.0 Xml;HDR=YES';"}
cn.Open()
' 创建表格
Dim cmd As New OleDbCommand("CREATE TABLE [Sheet1] (col1 Text, col2 Text)", cn)
cmd.ExecuteNonQuery()
' 依次写入每行数据
For Each row As DataGridViewRow In DataGridView1.Rows
Dim strInsert As String = "INSERT INTO [Sheet1$] (col1, col2) VALUES ('" & row.Cells(0).Value & "','" & row.Cells(1).Value & "')"
Dim cmdInsert As New OleDbCommand(strInsert, cn)
cmdInsert.ExecuteNonQuery()
Next
' 关闭连接
cn.Close()
End Sub
我们也可以使用第三方控件,例如 EPPlus,通过调用其 API 将 DataGridView 导出到 Excel。下面是一个示例代码:
' 将DataGridView导出到Excel
Private Sub ExportToExcel()
Using p As New ExcelPackage()
Dim ws As ExcelWorksheet = p.Workbook.Worksheets.Add("Sheet1")
' 写入DataGridView的列标题
For j As Integer = 0 To DataGridView1.Columns.Count - 1
ws.Cells(1, j + 1).Value = DataGridView1.Columns(j).HeaderText
Next
' 依次写入每行数据
For i As Integer = 0 To DataGridView1.Rows.Count - 1
For j As Integer = 0 To DataGridView1.Columns.Count - 1
ws.Cells(i + 2, j + 1).Value = DataGridView1.Rows(i).Cells(j).Value.ToString()
Next
Next
' 保存文件
p.SaveAs(New FileInfo("D:\ExcelFile.xlsx"))
End Using
End Sub
以上是将 DataGridView 导出到 Excel 的常用方法,可以根据自己的需求进行选择。