要使用VB.NET将DataGridView导出到Excel,您可以使用以下步骤:
Imports Excel = Microsoft.Office.Interop.Excel
Private Sub ExportDataGridViewToExcel(ByVal dgv As DataGridView, ByVal fileName As String)
Dim xlApp As Excel.Application = New Excel.Application
Dim xlWorkBook As Excel.Workbook = xlApp.Workbooks.Add(Type.Missing)
Dim xlWorkSheet As Excel.Worksheet = CType(xlWorkBook.Worksheets(1), Excel.Worksheet)
Dim xlRange As Excel.Range = xlWorkSheet.UsedRange
'将DataGridView的列标题添加到Excel工作表中
For col As Integer = 0 To dgv.Columns.Count - 1
xlWorkSheet.Cells(1, col + 1) = dgv.Columns(col).HeaderText
Next
'将DataGridView的数据添加到Excel工作表中
For row As Integer = 0 To dgv.Rows.Count - 1
For col As Integer = 0 To dgv.Columns.Count - 1
xlWorkSheet.Cells(row + 2, col + 1) = dgv.Rows(row).Cells(col).Value
Next
Next
'保存并关闭Excel工作簿
xlWorkBook.SaveAs(fileName)
xlWorkBook.Close()
'退出Excel应用程序
xlApp.Quit()
'释放COM对象
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlApp)
'显示导出成功消息
MessageBox.Show("DataGridView已成功导出到Excel文件。")
End Sub
Private Sub ReleaseComObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
End Try
End Sub
ExportDataGridViewToExcel(DataGridView1, "C:\DataGridView.xlsx")
这样,您就可以将DataGridView导出到Excel文件中了。
领取专属 10元无门槛券
手把手带您无忧上云