我正在开发一个由两部分组成的简单VB应用程序:
该类的代码如下:
Imports Microsoft.Office.Interop
Public Class MyClass
Public Function Excel_Calculate(ByVal p_File_Reference, ByVal p_Sheet_Reference, ByVal p_In_Cells_Values, ByVal p_Result_Cell, ByRef p_Result, ByRef p_Result_Code)
Console.WriteLine(" 1 ----- " & Now & "." & Now.Millisecond)
Dim l_List_of_Inputs() As String
Dim l_One_Cell_Address_Value() As String
Dim l_Counter As Integer
Console.WriteLine(" 1.1 ----- " & Now & "." & Now.Millisecond)
Dim Excel_Application As Excel.Application = CreateObject("excel.application") ' EXPENSIVE!!!!
Console.WriteLine(" 1.2 ----- " & Now & "." & Now.Millisecond)
Dim Excel_Workbooks As Excel.Workbooks = Excel_Application.Workbooks
Console.WriteLine(" 1.3 ----- " & Now & "." & Now.Millisecond)
Dim Excel_Workbook As Excel.Workbook
Console.WriteLine(" 1.4 ----- " & Now & "." & Now.Millisecond)
Dim Excel_WorkSheet As Excel.Worksheet
Console.WriteLine(" 2 ----- " & Now & "." & Now.Millisecond)
Dim l_One_Cell_Address As String
Dim l_One_Cell_Value As Double
Dim l_Return_Code As Integer
Excel_Application.Visible = False
Console.WriteLine(" 3 ----- " & Now & "." & Now.Millisecond)
Excel_Workbook = Excel_Workbooks.Open("C:\Users\Me\ABCD.xlsx", , True)
Console.WriteLine(" 4 ----- " & Now & "." & Now.Millisecond)
Excel_WorkSheet = Excel_Workbook.ActiveSheet
Console.WriteLine(" 5 ----- " & Now & "." & Now.Millisecond)
l_List_of_Inputs = Split(p_In_Cells_Values, ",")
For l_Counter = 0 To l_List_of_Inputs.Length - 1
l_One_Cell_Address_Value = Split(l_List_of_Inputs(l_Counter), ":")
l_One_Cell_Address = l_One_Cell_Address_Value(0)
l_One_Cell_Value = Convert.ToDouble(l_One_Cell_Address_Value(1))
Excel_WorkSheet.Range(l_One_Cell_Address).Value = l_One_Cell_Value
Next l_Counter
Console.WriteLine(" 6 ----- " & Now & "." & Now.Millisecond)
If (Trim(Excel_WorkSheet.Range(p_Result_Cell).Value) <> "") Then
p_Result = Excel_WorkSheet.Range(p_Result_Cell).Value
l_Return_Code = 0
Else
l_Return_Code = 2000
End If
Excel_Application.DisplayAlerts = False
Excel_Workbook.Close()
Excel_Application.Quit()
Excel_Workbook = Nothing
Console.WriteLine(" 7 ----- " & Now & "." & Now.Millisecond)
p_Result_Code = l_Return_Code
Return 0
End Function
End Class
在相当强大的机器上运行此操作需要2到3秒(经过时间)。在Excel中直接执行相同操作时,更新INPUT单元的响应时间小于可感知的时间。
我添加了一些打印件(请参阅代码)以找出主要延迟的位置,并生成的打印件为:
1 ----- 16/10/2017 14:15:59.209
1.1 ----- 16/10/2017 14:15:59.209
1.2 ----- 16/10/2017 14:16:00.354
1.3 ----- 16/10/2017 14:16:00.388
1.4 ----- 16/10/2017 14:16:00.388
2 ----- 16/10/2017 14:16:00.388
3 ----- 16/10/2017 14:16:00.389
4 ----- 16/10/2017 14:16:00.942
5 ----- 16/10/2017 14:16:00.970
6 ----- 16/10/2017 14:16:01.196
7 ----- 16/10/2017 14:16:01.235
意味着大部分时间都被消费:
重要的是要强调此服务必须允许执行Excel文件中的所有预定义计算。
任何人都可以建议为什么这需要这么长时间和/或另一种方法来实现这个功能?
谢谢!