我在vb.net中有一个datagridview,它从数据库中填充.我研究过,我发现没有内置的支持直接从datagridview打印.我不想使用水晶报告,因为我不熟悉它.
我打算将它导出到excel以使我能够从datagridview生成报告.
你能告诉我这样做的方法吗?
下面的代码创建Excel文件并将其保存在D:驱动器中
它使用Microsoft Office 2007
原文链接:https://www.f2er.com/vb/255921.html它使用Microsoft Office 2007
首先将READ REIDRANCE(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