2017-05-17 70 views
0

我正在使用excel-DNA示例作为此测试的基础。如何获得Excel更新Excel-DNA RTD电子表格?

我想excel每隔1秒在单元格B1中显示我的更新数据。

这工作正常约5秒,然后我得到一个计时器和必须等待功能完成只看到最后一个值。

如何在循环的每个循环中强制更新显示在电子表格中?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using ExcelDna.Integration; 
using System.Threading.Tasks; 
using System.Diagnostics;  

namespace BTPRTD 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
     } 
    } 

    public static class MyFunctions 
    { 
     public static MouseData MData; 

     [ExcelFunction(Description = "My first .NET function")] 
     public static string SayHello(string name) 
     { 
      //Debugger.Launch(); 
      MData = new MouseData(); 

      Task.Factory.StartNew(() => 
      {    
       ExcelAsyncUtil.QueueAsMacro(() => 
       { 
        KeepWritingData(); 
       }); 
      }); 
      return "Hello " + name; 
     } 

     public static void KeepWritingData() 
     { 
      var refB1 = new ExcelReference(0, 0, 1, 1, "Sheet1"); 
      string dataTxt = ""; 
      for (int i = 0; i < 100; i++) 
      { 
       try 
       { 
        MouseData .CurrentPriceData CPD = MData.GetCurrentPriceNT("White mouse"); 
        dataTxt = CPD.AsString(); 
       } 
       catch (Exception) 
       { 
        dataTxt = "Data Unavailable"; 
       } 

       refB1.SetValue("Ding: " + i + " " + dataTxt); 
       System.Threading.Thread.Sleep(1000); 
      } 
     } 
    } 
} 

回答

0

Excel支持一种名为RealTimeData(RTD)的工作表函数,它应该用于您的方案。

请参阅“Samples”GitHub存储库中的示例。在特殊情况下,看看RtdClocks example使用可观测定时器:

public static class RtdClock 
{ 
    [ExcelFunction(Description = "Provides a ticking clock")] 
    public static object dnaRtdClock_Rx() 
    { 
     string functionName = "dnaRtdClock_Rx"; 
     object paramInfo = null; // could be one parameter passed in directly, or an object array of all the parameters: new object[] {param1, param2} 
     return ObservableRtdUtil.Observe(functionName, paramInfo,() => GetObservableClock()); 
    } 

    static IObservable<string> GetObservableClock() 
    { 
     return Observable.Timer(dueTime: TimeSpan.Zero, period: TimeSpan.FromSeconds(1)) 
         .Select(_ => DateTime.Now.ToString("HH:mm:ss")); 
    } 
}