从数据表对象导出数据到Excel的高效方法

下面的代码做这个工作,但是完成执行需要将近60秒。 大约有2000行和55列。 我猜嵌套循环不是最有效和最专业的方式,我在谷歌search,但还没有find更好的办法…(我想也许有一种方法来使用SQL?)。 我会感谢提高这个任务的效率的build议。 (它写在vb.net但c#也很好的例子和build议)

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. 在数据表中select全部
  2. 复制
  3. 创buildxls文件

认真地我尝试了很多,但与标准的Win控件设置它是最快的。

upd语法这个你可以很容易地findnetworking,让我没有复制粘贴在这里

你也可能想检查这个http://closedxml.codeplex.com/

语法很简单,然后:

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