由 datagridview 控件向 Microsoft Excel 表格中导出

2008-10-25 22:55

适于 VB.net 2008 用的由 datagridview 控件向 Microsoft Excel 表格中导出的实例源代码。

说明:使用前,请完整安装 Microsoft Office 2007 (Office 12) 的各组件;并且在您的项目中引用 "Microsoft Excel 12.0 Object Library" 的 COM 加载项。

Private Function ExportExcel(ByVal dgv As DataGridView, ByVal IsOnlyVisible As Boolean) As Boolean

        ExportExcel = False
        Try
            Dim n, i, j, row, col As Integer
            Dim Excel2 As Microsoft.Office.Interop.Excel.Application = New Microsoft.Office.Interop.Excel.Application
            Excel2.Application.Workbooks.Add(True)
            col = 1
            '//记录列名
            For n = 0 To dgv.ColumnCount - 1
                If IsOnlyVisible Then
                    If dgv.Columns(n).Visible Then
                        Excel2.Cells(1, col) = dgv.Columns(n).HeaderText
                        col = col + 1
                    End If
                Else
                    Excel2.Cells(1, n + 1) = dgv.Columns(n).HeaderText
                End If

            Next
            '//记录内容
            row = 2
            ' col = 1

            For i = 0 To dgv.RowCount - 1
                col = 1
                For j = 0 To dgv.ColumnCount - 1
                    'System.Windows.Forms.Application.DoEvents()
                    If IsOnlyVisible Then
                        If dgv.Columns(j).Visible Then
                            Excel2.Cells(i + 2, col) = dgv.Rows(i).Cells(j).Value
                            col = col + 1
                        End If
                    Else
                        Excel2.Cells(i + 2, j + 1) = dgv.Rows(i).Cells(j).Value
                    End If
                Next

            Next
            Excel2.Visible = True
        Catch ex As Exception
            Throw ex
        End Try
        ExportExcel = True
       

    End Function

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值