如何将数据导入繁重的Excel文件

目标

将大约100多行数据导入到工作表中。 很快。

目前的问题

Excel文件不是很大(甚至不到1MB)。 虽然,我们使用这个Excel文件与SolidEdge进行通信,这使得它非常沉重。

目前,大约需要60秒来填充100行数据。 不要误解我的意思,那不是很长。 而我用一个新的空Excel文件进​​行了testing,花了不到1秒的时间填充数据。

这是我的代码incase我在那里做了一些愚蠢的事情:

Private Sub PopulateExcel() Dim xlApp As Excel.Application = Nothing Dim xlWorkBooks As Excel.Workbooks = Nothing Dim xlWorkBook As Excel.Workbook = Nothing Dim xlWorkSheet As Excel.Worksheet = Nothing Dim xlWorkSheets As Excel.Sheets = Nothing Dim Proceed As Boolean = False Dim RowIndex As Integer = 2 Dim counter As Integer = 0 xlApp = CType(Marshal.GetActiveObject("Excel.Application"), Excel.Application) xlWorkBooks = xlApp.Workbooks For Each wb As Excel.Workbook In xlWorkBooks If wb.Name.Contains("301-AAAA-00X") Then xlWorkBook = wb xlWorkSheets = xlWorkBook.Sheets Exit For End If Next If xlWorkSheets IsNot Nothing Then For x As Integer = 1 To xlWorkSheets.Count xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet) If xlWorkSheet.Name = "ImportSheet" Then Proceed = True Exit For End If Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet) xlWorkSheet = Nothing Next End If If Proceed Then tspbProgress.Value = 0 tspbProgress.Maximum = dic_Vars.Count tspbProgress.Visible = True For Each key As KeyValuePair(Of String, String) In dic_Vars 'Contains all my the data tsslStatus.Text = "Populating Excel: " & key.Key & " | " & key.Value xlWorkSheet.Cells(RowIndex, 2).value = key.Key xlWorkSheet.Cells(RowIndex, 3).value = key.Value RowIndex += 1 IncProg() Next tspbProgress.Visible = False ReleaseComObject(xlWorkSheets) ReleaseComObject(xlWorkSheet) ReleaseComObject(xlWorkBook) ReleaseComObject(xlWorkBooks) ReleaseComObject(xlApp) End If End Sub Private Sub ReleaseComObject(ByRef obj As Object) Try System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) obj = Nothing Catch ex As Exception obj = Nothing End Try End Sub 

结论

我想创build一个新的Excel文件,在那里导入数据,只是复制/粘贴到我们使用的真正的Excel文件。

有什么build议么?

很高兴拜伦墙帮我find答案。 我现在使用数组input我的数据,而不是遍历每个单元格。

我创build我的数组并根据我的variables字典有多大来填充它。 然后使用下面的Resize()方法创build一个新的范围。

一旦完成,一切都瞬间完成!

  Dim arrNames(,) As String = New String(AscW(ChrW(dic_Vars.Count)), 1) {} Dim arrValues(,) As String = New String(AscW(ChrW(dic_Vars.Count)), 1) {} Dim i As Integer = 0 For Each key As KeyValuePair(Of String, String) In dic_Vars arrNames(i, 0) = key.Key arrValues(i, 0) = key.Value i += 1 Next If Proceed Then Dim r As Microsoft.Office.Interop.Excel.Range = xlWorkSheet.Range("B2").Resize(arrNames.GetLength(0)) Dim r2 As Microsoft.Office.Interop.Excel.Range = xlWorkSheet.Range("C2").Resize(arrValues.GetLength(0)) r.Value2 = arrNames r2.Value2 = arrValues ReleaseComObject(xlWorkSheets) ReleaseComObject(xlWorkSheet) ReleaseComObject(xlWorkBook) ReleaseComObject(xlWorkBooks) ReleaseComObject(xlApp) End If