Jak utworzyć dodatek automatyzacji Excel w czasie rzeczywistym w C# przy użyciu RtdServer?
Miałem za zadanie napisać dodatek automatyzacji Excela w czasie rzeczywistym w C# przy użyciu RtdServer for work. Polegałem w dużej mierze na wiedzy, na którą natknąłem się w Stack Overflow. Postanowiłem wyrazić moje podziękowania, pisząc jak udokumentować, że łączy ze sobą wszystko, czego się nauczyłem. Kenny Kerr ' s Excel RTD Servers: Minimal C# Implementation artykuł pomógł mi zacząć. Szczególnie pomocne okazały się dla mnie komentarze Mike ' a Rosenbluma i Goverta.
3 answers
(jako alternatywę dla podejścia opisanego poniżej należy rozważyć użycie Excel-DNA . Excel-DNA pozwala na zbudowanie serwera RTD bez rejestracji. Rejestracja COM wymaga uprawnień administracyjnych, które mogą prowadzić do problemów z instalacją. Biorąc to pod uwagę, poniższy kod działa dobrze.)
Aby utworzyć dodatek automatyzacji Excela w czasie rzeczywistym w C# przy użyciu RtdServer:1) Utwórz projekt biblioteki klas C# w Visual Studio i wpisz "following": {]}
using System;
using System.Threading;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;
namespace StackOverflow
{
public class Countdown
{
public int CurrentValue { get; set; }
}
[Guid("EBD9B4A9-3E17-45F0-A1C9-E134043923D3")]
[ProgId("StackOverflow.RtdServer.ProgId")]
public class RtdServer : IRtdServer
{
private readonly Dictionary<int, Countdown> _topics = new Dictionary<int, Countdown>();
private Timer _timer;
public int ServerStart(IRTDUpdateEvent rtdUpdateEvent)
{
_timer = new Timer(delegate { rtdUpdateEvent.UpdateNotify(); }, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
return 1;
}
public object ConnectData(int topicId, ref Array strings, ref bool getNewValues)
{
var start = Convert.ToInt32(strings.GetValue(0).ToString());
getNewValues = true;
_topics[topicId] = new Countdown { CurrentValue = start };
return start;
}
public Array RefreshData(ref int topicCount)
{
var data = new object[2, _topics.Count];
var index = 0;
foreach (var entry in _topics)
{
--entry.Value.CurrentValue;
data[0, index] = entry.Key;
data[1, index] = entry.Value.CurrentValue;
++index;
}
topicCount = _topics.Count;
return data;
}
public void DisconnectData(int topicId)
{
_topics.Remove(topicId);
}
public int Heartbeat() { return 1; }
public void ServerTerminate() { _timer.Dispose(); }
[ComRegisterFunctionAttribute]
public static void RegisterFunction(Type t)
{
Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(@"CLSID\{" + t.GUID.ToString().ToUpper() + @"}\Programmable");
var key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(@"CLSID\{" + t.GUID.ToString().ToUpper() + @"}\InprocServer32", true);
if (key != null)
key.SetValue("", System.Environment.SystemDirectory + @"\mscoree.dll", Microsoft.Win32.RegistryValueKind.String);
}
[ComUnregisterFunctionAttribute]
public static void UnregisterFunction(Type t)
{
Microsoft.Win32.Registry.ClassesRoot.DeleteSubKey(@"CLSID\{" + t.GUID.ToString().ToUpper() + @"}\Programmable");
}
}
}
2) Kliknij prawym przyciskiem myszy projekt i Dodaj > nowy element... > Klasa Instalatora. Przełącz do widoku kod i wpisz:
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace StackOverflow
{
[RunInstaller(true)]
public partial class RtdServerInstaller : System.Configuration.Install.Installer
{
public RtdServerInstaller()
{
InitializeComponent();
}
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]
public override void Commit(IDictionary savedState)
{
base.Commit(savedState);
var registrationServices = new RegistrationServices();
if (registrationServices.RegisterAssembly(GetType().Assembly, AssemblyRegistrationFlags.SetCodeBase))
Trace.TraceInformation("Types registered successfully");
else
Trace.TraceError("Unable to register types");
}
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
var registrationServices = new RegistrationServices();
if (registrationServices.RegisterAssembly(GetType().Assembly, AssemblyRegistrationFlags.SetCodeBase))
Trace.TraceInformation("Types registered successfully");
else
Trace.TraceError("Unable to register types");
}
public override void Uninstall(IDictionary savedState)
{
var registrationServices = new RegistrationServices();
if (registrationServices.UnregisterAssembly(GetType().Assembly))
Trace.TraceInformation("Types unregistered successfully");
else
Trace.TraceError("Unable to unregister types");
base.Uninstall(savedState);
}
}
}
3) Kliknij prawym przyciskiem myszy na właściwości projektu i zaznacz: aplikacja > Informacje o montażu... > Make assembly COM-Visible and Build > Register for COM Interop
3.1) kliknij prawym przyciskiem myszy na projekcie Dodaj referencję... > Zakładka. NET > Microsoft.Biuro.Interop.Excel
4) Build Solution (F6)
5) Run Excel. Przejdź do Opcje programu Excel > Dodatki > Zarządzaj dodatkami programu Excel > Automatyzacja i wybierz " StackOverflow.RtdServer "
6) Enter " = RTD ("StackOverflow.RtdServer.",, 200) " do celi.
7) trzymajcie kciuki i miejmy nadzieję, że to zadziała!
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-29 00:01:18
Wywołanie UpdateNotify z wątku timera spowoduje w końcu dziwne błędy lub rozłączenia z programem Excel.
Metoda UpdateNotify () musi być wywołana tylko z tego samego wątku, który wywołuje Serverstart (). Nie jest to udokumentowane w Pomocy RTDServer, ale jest to ograniczenie COM.
Poprawka jest prosta. Użyj DispatcherSynchronizationContext, aby przechwycić wątek wywołujący ServerStart i użyj go do wysyłania wywołań do UpdateNotify:
public class RtdServer : IRtdServer
{
private IRTDUpdateEvent _rtdUpdateEvent;
private SynchronizationContext synchronizationContext;
public int ServerStart( IRTDUpdateEvent rtdUpdateEvent )
{
this._rtdUpdateEvent = rtdUpdateEvent;
synchronizationContext = new DispatcherSynchronizationContext();
_timer = new Timer(delegate { PostUpdateNotify(); }, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
return 1;
}
// Notify Excel of updated results
private void PostUpdateNotify()
{
// Must only call rtdUpdateEvent.UpdateNotify() from the thread that calls ServerStart.
// Use synchronizationContext which captures the thread dispatcher.
synchronizationContext.Post( delegate(object state) { _rtdUpdateEvent.UpdateNotify(); }, null);
}
// etc
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-26 04:31:48
Po dwóch poprzednich odpowiedziach dla serwera RTD zadziałało dla mnie. Jednak napotkałem problem, gdy na maszynie x64 z Excelem x64. W moim przypadku, dopóki nie zmieniłem "platformy docelowej" projektu na x64, Excel zawsze pokazywał #N / A.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-02 16:31:48