提高MS Excel的书写性能
-
27-09-2019 - |
题
我面临性能问题,同时读/写从/数据到MS-Excel单元。我使用的MS Excel 11.0对象库用于与VB.NET自动化。
目前它需要太多的时间来阅读和从/到Excel文件的写。 (10分钟读取1000行:()。看来细胞通过细胞读写方法并不那effiecient。是否有任何方式来读/使用批量操作的写入数据?
解决方案
,而不是由小区读取细胞你能读的整个范围,并将其保存为2D arrray。然后,可以访问该2D阵列,你会在Excel接入小区。
我没有很好地精通VB.NET为Excel对象,但如果你了解C#,然后给这个链接一个快速阅读,并尝试执行它。
http://dotnetperls.com/excel-interop 读取“获得的工作簿数据”部分
其他提示
大!!!
我使用2D阵列的方法,取得了巨大的性能提升!!
我以前所使用的细胞通过细胞aprroach如下所示,
Dim cell As Excel.Range = Nothing
cell = sheet.Cells(rowIndex, colIndex)
cell.Value = "Some value"
我用于迭代单元格区域以及用于将值中的每个单元格复制。
这里每sheet.Cells
和cell.Value
是一个互操作调用和对每个呼叫它给调用EXCEL.EXE,花费更多的时间。
在2D方法我已经填补了的数据,这是在Excel细胞被复制,在2D阵列,然后将2D阵列分配给小区的选择reange的值。它是如下所示,
Dim darray(recordCount - 1, noOfCol - 1) As String
//Fill the data in darray
//startPosRange = Get the range of cell from where to start writing data
startPosRange = startPosRange.Resize(recordCount, noOfCol)
startPosRange.Value = darray
这些修改后,我所收集的性能数据的方法和结果都是令人惊讶地大!!。的后一种方法是25倍的速度前一个强>
类似地,我已经使用了2D阵列的方法,用于读取从单元中的数据和观察到的类似的性能提升。代码示例如下所示。
细胞通过细胞的方法,
Dim usedRange As Excel.Range = sheet.UsedRange
For Each row As Excel.Range In usedRange.Rows()
For Each cellData As Excel.Range In row.Cells
//Gather cellData.Value in some container.
Next
2D阵列的方法,
Dim usedRange As Excel.Range = sheet.UsedRange
//Here the array index starts from 1. why???
Dim darray(,) As Object = CType(usedRange.Value, Object(,))
Dim rows As Integer = darray.GetUpperBound(0)
Dim cols As Integer = darray.GetUpperBound(1)
For i As Integer = 1 To rows
For j As Integer = 1 To cols
Dim str As String
If darray(i, j) Is Nothing Then
str = ""
Else
str = darray(i, j).ToString
End If
//Use value of str
Next
Next
请参阅, http://support.microsoft.com/kb/306023 , http://dotnetperls.com/excel-interop (感谢ChickSentMeHighE中的链接)
享受性能!!!