Search code examples
c#excelinteropoffice-interop

C# Write to an open Excel file using Interop


I am having a ridiculously hard time with this, but I need to be able to connect to an open excel file using Interop and then write to that file.

The file is opened by an outside process and then this application comes in later to write to the workbook. I can get it to open a file and write to the active workbook. but I can't find a way to connect to a previous workbook and write.

I had been using Marshal.GetActiveObject but I will soon be running the application on a computer with multiple files open and need to write to one that will most likely not bee the active one.


Solution

  • Update :

    System.Runtime.InteropServices.Marshal.BindToMoniker can be used to access file that is opened in Excel, or opens it if it is not already opened :

    var wb = Marshal.BindToMoniker(@"C:\x.xlsx") as Microsoft.Office.Interop.Excel.Workbook; 
    

    https://blogs.msdn.microsoft.com/eric_carter/2009/03/12/attaching-to-an-already-running-office-application-from-your-application-using-getactiveobject-or-bindtomoniker/


    Old answer :

    GetObject can be used with reference to Microsoft.VisualBasic (it also opens the file if needed) :

    object o = Microsoft.VisualBasic.Interaction.GetObject(@"C:\x.xlsx", "Excel.Application");
    var wb = o as Microsoft.Office.Interop.Excel.Workbook; 
    if (wb != null) 
    { 
        Microsoft.Office.Interop.Excel.Application xlApp = wb.Application;
        // your code 
    }
    

    Reference to Microsoft.VisualBasic can probably be avoided by checking the GetObject source code https://github.com/Microsoft/referencesource/blob/master/Microsoft.VisualBasic/runtime/msvbalib/Interaction.vb#L1039