提高MS Excel写作的性能

在从/向MS-Excel单元读取/写入数据时,我遇到性能问题。 我正在使用MS Excel 11.0对象库与VB.NET自动化。

目前,从Excel文件读取和写入需要花费太多时间。 (10分钟读取1000行:()。看起来单元格的读写方式并不是那么高效。是否有任何方式使用批量操作来读/写数据?

而不是逐个阅读细胞,你可以阅读一个完整的范围,并保存到一个2D arrray。 然后,您可以像访问Excel中的单元格一样访问二维数组。

我不是精通VB.NET的excel对象,但如果你了解C#,那么给这个链接快速阅读并尝试实现它。

http://dotnetperls.com/excel-interop阅读“获取工作簿数据”部分

大!!!

我用二维数组的方法,并取得了巨大的性能提升!

以前我使用了如下所示的逐个单元格的错误,

Dim cell As Excel.Range = Nothing cell = sheet.Cells(rowIndex, colIndex) cell.Value = "Some value" 

我曾经遍历一个单元格的范围,并用于复制每个单元格中的值。 在这里,每个sheet.Cellscell.Value是一个互操作调用,每调用一次,它都会调用Excel.exe,这会花费更多的时间。

在二维方法中,我将二维数组中要填充的数据复制到Excel单元格中,然后将二维数组分配给所选单元格的值。 如下所示,

 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的链接)

享受表演!