在从MS-Excel单元格读取数据或向MS-Excel单元格写入数据时,我遇到了性能问题。我使用MS Excel11.0对象库来实现VB.NET的自动化。
目前,从Excel文件读取和写入Excel文件需要花费太多时间。(10分钟读取1000行:( )。似乎逐个单元的读取和写入方法并不是那么有效。有没有办法使用批量操作来读/写数据?
发布于 2010-08-09 22:41:44
您可以读取整个范围并将其保存到2D数组中,而不是逐个单元格地读取。然后,您可以像访问excel中的单元格一样访问二维数组。
我不是很精通excel对象的VB.NET,但是如果你理解C#,那么快速阅读这个链接,并尝试实现它。
http://dotnetperls.com/excel-interop阅读“获取工作簿数据”部分
发布于 2010-08-10 14:56:48
好极了!
我使用了2D数组方法,并实现了巨大的性能提升!!。
之前我使用的是一个接一个的方法,如下所示:
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数组赋给所选区域的值。如下所示:
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倍。
同样,我使用二维数组方法从单元中读取数据,并看到了类似的性能提升。代码示例如下所示。
逐个细胞的方法,
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
二维数组方法,
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提供的链接)
享受表演吧!
https://stackoverflow.com/questions/3440981
复制相似问题