Get instance of Excel application with C# by Handle

后端 未结 3 1518
广开言路
广开言路 2020-11-28 09:16

I have a c# simple application that have to write some values in a excel ranges of a specific worksheet. I create an instance of Excel application if not exist, but if exist

3条回答
  •  温柔的废话
    2020-11-28 10:11

    Use the following code to get the first running instance of Excel:

    oExcelApp =  (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
    

    Example

    public Excel.Application StartExcel()
    {
        Excel.Application instance = null;
        try
        {
           instance = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
        }
        catch (System.Runtime.InteropServices.COMException ex)
        {
           instance = new Excel.ApplicationClass();
        }
    
        return instance;
    }
    

提交回复
热议问题