I have excel with the Bloomberg API ( which uses simple calls like =BDP(\"MS equity\",\"ask\") ). I also have a C# application that opens an excel file (through interop) tha
I was able to get a similar result using NetOffice. This particular function will retrieve the last started instance of the excel process or create a new one if one does exist. From there you are free to open/create a new workbook.
The nice thing about using netoffice and this approach is that it doesn't depend on version specific interop DLLs and if you dispose of the NetOffice objects then all of the excel COM objects are cleaned up properly.
using Xl = NetOffice.ExcelApi;
private static Xl.Application GetOrStartExcel(bool started = false)
{
Xl.Application application = null;
try
{
object nativeProxy = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
application = new Xl.Application(null, nativeProxy);
return application;
}
catch (Exception ex)
{
if (!started) Process.Start("excel.exe");
Thread.Sleep((int) TimeSpan.FromSeconds(1).TotalMilliseconds);
return GetOrStartExcel(true);
}
}
Usage:
using (var excel = GetOrStartExcel())
{
//Do work with excel object
}