我需要每天从SQLServer向Excel导出大量(近一百万)个数据。数据正在通过存储过程处理,然后我将它们放在DataSet上并尝试使用以下代码导出:
` Private Sub ExportToExcel(ByVal dtTemp As System.Data.DataTable,ByVal filepath As String) Dim strFileName As String = filepath
Dim _excel As New Excel.Application
Dim wBook As Excel.Workbook
Dim wSheet As Excel.Worksheet
wBook = _excel.Workbooks.Add()
wSheet = wBook.ActiveSheet()
Dim dt As System.Data.DataTable = dtTemp
Dim dc As System.Data.DataColumn
Dim dr As System.Data.DataRow
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
wSheet.Cells(1, colIndex) = dc.ColumnName
Next
For Each dr In dt.Rows
rowIndex = rowIndex + 1
colIndex = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
wSheet.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
wSheet.Columns.AutoFit()
wBook.SaveAs(strFileName)
ReleaseObject(wSheet)
wBook.Close(False)
ReleaseObject(wBook)
_excel.Quit()
ReleaseObject(_excel)
GC.Collect()
End Sub`
有没有更快的方法呢? DataSet到剪贴板怎么样然后粘贴到excel?
答案 0 :(得分:2)
一种方法是将DataSet保存为XML file:
myDataSet.WriteXml("c:\file.xml")
答案 1 :(得分:0)
有一种更快的方式涉及SQL数据泵(导入导出DTS)。您可以保存DTS包(将数据从SQL导出到Excel大约每秒1000行),然后使用SQL Server代理运行该包。这样,您就不必逐个迭代到所有行和列,并且您不需要拥有VB代码。