旨在实现: 想要将获取的表转储到Excel工作表。
我的实施:
Imports System.Data.OleDb
Private Sub getRawDataNextMonth()
Dim sheetName As String = "RawData"
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\rawData.xlsx;Extended Properties=""Excel 12.0 XML;""")
Dim adapter As New Data.OleDb.OleDbDataAdapter("SELECT * FROM [Sheet1$]", con)
Dim dataSet As New Data.DataSet
adapter.Fill(dataSet)
Dim dataTable As Data.DataTable = dataSet.Tables(0)
Dim rawData(dataTable.Rows.Count, dataTable.Columns.Count - 1) As Object
Dim range As Excel.Range = WB.Sheets(sheetName).Range("A2:T" + dataTable.Rows.Count.ToString())
For col = 0 To dataTable.Columns.Count - 1
For row = 0 To dataTable.Rows.Count - 1
rawData(row, col) = dataTable.Rows(row).ItemArray(col)
Next
Next
range.Value2 = rawData
End Sub
我是数据提取和ADO.Net概念的新手,并且刚刚开始工作。 但..
这对我来说似乎非常低效和蹩脚。
那么,您能帮助降低复杂性并提高绩效吗?
欢迎完全不同(更好)的实施!
请帮助我根据您的经验优化这一点!
答案 0 :(得分:1)
此功能以CSV格式写入文本文件,然后在Excel中打开文件并将其另存为xlsx格式。我尝试使用53列x 10,000行表,花了大约2秒钟:
Private Sub Export3(ByVal filename As String, ByRef dt As DataTable)
Dim tempfile As String = Path.GetTempPath + Path.GetFileNameWithoutExtension(Path.GetTempFileName) + ".csv"
Dim sb As StringBuilder
Using sw As StreamWriter = New StreamWriter(tempfile)
sb = New StringBuilder("")
For c As Integer = 0 To dt.Columns.Count - 1
sb.Append(dt.Columns(c).ColumnName + ",")
Next
sw.WriteLine(sb.ToString.TrimEnd(","c))
For r As Integer = 0 To dt.Rows.Count - 1
sb = New StringBuilder("")
For c As Integer = 0 To dt.Columns.Count - 1
sb.Append(dt.Rows(r).Item(c).ToString + ",")
Next
sw.WriteLine(sb.ToString.TrimEnd(","c))
Next
End Using
Dim xlApp As Excel.Application = Nothing
Dim xlBook As Excel.Workbook = Nothing
Try
xlApp = New Excel.Application
'xlApp.Visible = True 'for debugging
xlApp.DisplayAlerts = False
xlBook = xlApp.Workbooks.Open(tempfile)
xlBook.SaveAs(filename, Excel.XlFileFormat.xlWorkbookDefault)
My.Computer.FileSystem.DeleteFile(tempfile)
Finally
If Not IsNothing(xlBook) Then
xlBook.Close()
End If
If Not IsNothing(xlApp) Then xlApp.Quit()
End Try
End Sub