gpt4 book ai didi

vb.net - 如何使用vb.net将datagridview导出到excel?

转载 作者:行者123 更新时间:2023-12-02 08:50:56 25 4
gpt4 key购买 nike

我在 vb.net 中有一个 datagridview,它是从数据库填充的。我进行了研究,发现没有内置支持直接从 datagridview 打印。我不想使用 Crystal 报表,因为我对它不熟悉。

我计划将其导出到 Excel,以便我能够从 datagridview 生成报告。

你能给我提供一些方法吗?

最佳答案

下面的代码创建 Excel 文件并将其保存在 D: 驱动器中它使用 Microsoft Office 2007

首先将引用(Microsoft Office 12.0 对象库)添加到您的项目

然后将下面给出的代码添加到“导出”按钮单击事件-

Private Sub Export_Button_Click(ByVal sender As System.Object, ByVal e As 
System.EventArgs) Handles VIEW_Button.Click

Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer

xlApp = New Microsoft.Office.Interop.Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")


For i = 0 To DataGridView1.RowCount - 2
For j = 0 To DataGridView1.ColumnCount - 1
For k As Integer = 1 To DataGridView1.Columns.Count
xlWorkSheet.Cells(1, k) = DataGridView1.Columns(k - 1).HeaderText
xlWorkSheet.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString()
Next
Next
Next

xlWorkSheet.SaveAs("D:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()

releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)

MsgBox("You can find the file D:\vbexcel.xlsx")
End Sub

Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub

关于vb.net - 如何使用vb.net将datagridview导出到excel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/680199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com