我一直在尝试编写一个可以从excel文件中读取数据的程序。经过几个小时的尝试,它终于奏效了。但是,我注意到它工作得很慢,特别是涉及到大量的行和列时。在我的另一台PC上试过它只是为了检查它可能是一个PC问题但不幸的是它在其他人身上肯定也很慢。
我需要更改或删除或添加某些内容吗?
这是我的代码:
Public Sub LoopExcel()
Dim colfrom As Integer = Asc(txtColFrom.Text)
Dim colto As Integer = Asc(txtColTo.Text)
Dim rowfrom As Integer = Integer.Parse(txtRowFrom.Text)
Dim rowto As Integer = Integer.Parse(txtRowTo.Text)
For rowindex = rowfrom To rowto
For colindex = colfrom To colto
Dim str As String = OpenExcelGetData(txtFileName.Text, rowindex, Convert.ToChar(colindex)).ToString
Console.WriteLine(str)
Next
Next
End Sub
Public Function OpenExcelGetData(ByVal fileNameAndPath As String, ByVal rowIndex As Integer, ByVal columnIndex As String) As Object
Dim oExcelApp As New Excel.ApplicationClass
Dim oExcelBook As Excel.Workbook
Dim oExcelSheet As Excel.Worksheet
Dim sheetNumber As Integer = 1 '1-based array
Dim oData As Object = Nothing
Try
oExcelBook = oExcelApp.Workbooks.Open(fileNameAndPath)
oExcelSheet = CType(oExcelBook.Worksheets(sheetNumber), Excel.Worksheet)
'Read data
Dim excelRange As String = columnIndex & rowIndex.ToString()
oData = oExcelSheet.Range(excelRange).Value
Catch exp As COMException
MessageBox.Show(exp.Message)
Catch exp As Exception
MessageBox.Show(exp.Message)
End Try
Return oData
End Function
答案 0 :(得分:1)
您应该考虑到COM技术本身很慢。 您需要最小化调用方法的数量,逐个单元格将非常缓慢,可能是范围。
您可能还会想到一个不涉及COM的不同解决方案。