Windows Phone Developers

Wednesday, January 7, 2009

How to use Existing Instance of Excel in C#



C# GetObject Method

Marshal.GetActiveObject gets a running instance of the specified object from the Running Object Table (ROT).

using System.Runtime.InteropServices;

using Excel = Microsoft.Office.Interop.Excel;

private void GetExcel()

{

try

{

oXL = (Excel.Application)Marshal.GetActiveObject("Excel.Application");

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

}

}

Marshal.GetActiveObject exposes the GetActiveObject COM API method from OLEAUT32.DLL; however, the latter expects a class identifier (CLSID) instead of the programmatic identifier (ProgID) expected by this method. To obtain a running instance of a COM object without a registered ProgID, use platform invoke to define the GetActivateObject COM method


Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

5 comments:

  1. The above works, however once you find the instance of the Excel process I can't figure out how to force it to be visible.

    I've tried all sorts of things like setting the VISIBLE property to TRUE with no luck.

    Ideas?

    ReplyDelete
  2. I'm using Windows Vista Ultimate 32 bits with Microsoft Excel 2007 and this code doesn't work. I tried Microsoft.VisualBasic.Interop.GetObject and didn't work too......................

    ReplyDelete
  3. It works for me in 32 Bit Vista. Any way to reproduce the error you get! For example, is the Excel used by any other program?

    ReplyDelete
  4. No, my Excel is not used by any other program. What I am trying to do it is simple in Visual Basic 6.0. I just want do manually open an Excel File, and after I want that my c# program read and write contents of this opened worksheet.

    If your code is working, could you show us how u implement? Or better: give us a sample that makes what I said above.

    Thank You

    ReplyDelete
  5. Here are the ways that I have tried :

    Type 1:


    foreach (System.Diagnostics.Process oXLApp in System.Diagnostics.Process.GetProcessesByName("Excel"))
    {

    MessageBox.Show(oXLApp.MainWindowTitle);
    IntPtr xLHandle = oXLApp.Handle;
    Type t1 = oXLApp.GetType();
    Delegate oX2L = Marshal.GetDelegateForFunctionPointer (xLHandle, t1);
    //String XLProgID = Marshal.GenerateProgIdForType(XLSafeType);
    oXL = (Excel.Application)Marshal.GetActiveObject(oXLApp.Id.ToString());
    //oXL = (Excel.Application)oXLApp.CreateObjRef ;
    }

    Type 2:

    oXL = (Excel.Application)Marshal.GetActiveObject("Excel.Application");

    Excel.Workbook oWB = oXL.Workbooks.Open(sXLFileName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);

    ReplyDelete