Excel interop loading XLLs and DLLs

后端 未结 4 1505
南笙
南笙 2020-12-03 04:14

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

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 04:46

    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
    }
    

提交回复
热议问题