VB.NET把DataTable里的内容导出到EXCEL

在程序的引用中添加对Excel的引用.

添加引用Microsoft Excel 9.0 Object Library后

Function SendToExcel(ByVal Table As DataTable, ByVal SheetName As String)

    Dim oExcel As New Excel.Application

    Dim obook As Excel.Workbook

    Dim oSheet As Excel.Worksheet

    Try

        obook = oExcel.Workbooks.Add '.Open(file)

        oSheet = obook.Worksheets(1)

        oSheet.Name = SheetName

        Dim r As Integer, c As Integer

        Dim rCount As Integer

        Dim cCount As Integer

        rCount = Table.Rows.Count

        cCount = Table.Columns.Count()

        For c = 1 To cCount

            oSheet.Cells(1, c) = Table.Columns(c - 1).Caption '设置列标题

        Next

        c = 0 : r = 0

        For r = 1 To rCount

            For c = 1 To cCount

                oSheet.Cells(r + 1, c) = CStr(Table.Rows(r - 1)(c - 1).ToString)

            Next

        Next

        oExcel.Visible = True

    Catch ex As Exception

        MsgBox(ex.Message)

    End Try

    oExcel = Nothing

    obook = Nothing

    oSheet = Nothing

End Function

第二种方法:

'把DataTable里的内容导出到EXCEL,执行代码就行,什么都不用改,什么都不用设置

Private Sub toExcel(ByVal tb As DataTable)

            Dim   dgrid   As   System.Web.UI.WebControls.DataGrid   =   Nothing

            Dim   context   As   System.Web.HttpContext   =   System.Web.HttpContext.Current

            Dim   strOur   As   System.IO.StringWriter   =   Nothing

            Dim   htmlWriter   As   System.Web.UI.HtmlTextWriter   =   Nothing

            If   Not   IsNothing(tb)   Then

                    if tb.rows.count=0 then exit sub

                    context.Response.ContentType   =   "application/vnd.ms-excel "

                    context.Response.ContentEncoding   =   System.Text.Encoding.UTF7

                    context.Response.Charset   =   " "

                    strOur   =   New   IO.StringWriter

                    htmlWriter   =   New   System.Web.UI.HtmlTextWriter(strOur)

                    dgrid   =   New   DataGrid

                    dgrid.DataSource   =   tb.DefaultView

                    dgrid.AllowPaging   =   False

                    dgrid.DataBind()

                    dgrid.RenderControl(htmlWriter)

                    context.Response.Write(strOur.ToString)

                    context.Response.End()

            End   If 

End Sub

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值