如何使用 vb.net 将 datagridview 导出到 excel? [英] How to export datagridview to excel using vb.net?

查看:37
本文介绍了如何使用 vb.net 将 datagridview 导出到 excel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 vb.net 中有一个从数据库填充的 datagridview.我已经研究过,我发现没有内置支持直接从 datagridview 打印.我不想使用水晶报表,因为我不熟悉它.

I have a datagridview in vb.net that is filled up from the database. I've researched and I found out that there is no built in support to print directly from datagridview. I don't want to use crystal report because I'm not familiar with it.

我打算将它导出到 excel 以便我能够从 datagridview 生成报告.

I'm planning to export it to excel to enable me to generate report from the datagridview.

你能告诉我这样做的方法吗?

Can you provide me ways to do this?

推荐答案

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

Code below creates Excel File and saves it in D: drive It uses Microsoft office 2007

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

FIRST ADD REFERRANCE (Microsoft office 12.0 object library ) to your project

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

Then Add code given bellow to the Export button click event-

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 将 datagridview 导出到 excel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆