将数据从datatable对象导出到Excel的有效方法

时间:2015-10-03 12:38:13

标签: c# vb.net excel datatable

下面的代码完成了这项工作,但完成执行需要将近60秒。大约有2000行和55列。我猜一个嵌套循环不是最有效和最专业的方式,我在谷歌搜索但没有找到更好的方法......(我想也许有办法使用SQL?)。我将感谢有关使这项任务更有效的建议。 (它用vb.net编写,但c#也适用于示例和建议)

   Public Sub LoadDataTableToExcell(ByVal d As DataTable, ByVal path As String, ByVal fileName As String, ByVal newFile As Boolean, ByVal sheetName As String)

   If CheckIfDirExist(path) = False Then
            MsgBox("the Path" & " " & path & " " & "Does not exist")
            Exit Sub
        End If
        CreateAnExcelFile(path, sheetName)

        Dim xlapp As New Excel.Application
        Dim ws As Excel.Worksheet
        Dim xlworkbook As Excel.Workbook

        xlworkbook = xlapp.Workbooks.Open(path)
        ws = xlworkbook.Sheets(sheetName)
        Dim Erows As Integer = Nothing
        Dim Ecolumns As Integer = Nothing

        For Ecolumns = 0 To d.Columns.Count - 1
            ws.Cells(1, Ecolumns + 1) = d.Columns(Ecolumns).ColumnName
            For Erows = 0 To d.Rows.Count - 1
                ws.Cells(Erows + 3, Ecolumns + 1) = d.Rows(Erows).Item(Ecolumns)
            Next
        Next


        Dim CarbonNewRng As Excel.Range

        CarbonNewRng = ws.Range(ws.Cells(1, 1), ws.Cells(d.Rows.Count + 2, d.Columns.Count))
        CarbonNewRng.Borders.Weight = 4
        CarbonNewRng.Borders.Color = Color.FromArgb(0, 64, 64)

        ws.Columns("A:AZ").autofit()

        xlworkbook.Save()
        xlworkbook.Close()
        xlapp.Quit()



        releaseObject(xlapp)
        releaseObject(ws)
        releaseObject(xlworkbook)


        xlworkbook = Nothing
        xlapp = Nothing
        ws = Nothing
    Else

    End If
 end sub

1 个答案:

答案 0 :(得分:1)

这很奇怪,但最快的方法是最狡猾的方式:

  1. 全部选择数据表
  2. 复制
  3. 创建xls文件
  4. 粘贴
  5. 说真的,我尝试了很多,但是使用标准的Win控件设置它是最快的。

    你可以通过网轻松找到

    upd 这个语法,让我不要复制粘贴在这里

    您也可以查看此http://closedxml.codeplex.com/

    语法非常简单:

    XLWorkbook wb = new XLWorkbook();
    DataTable dt = GetDataTableOrWhatever();
    wb.Worksheets.Add(dt,"WorksheetName");