Search code examples
c#office-interopoffice-addinsexcel-interopexcel-addins

How to run Interop.Excel.Application with command arguments?


I need to pass arguments to new instance of excel and then read arguments from new instance via Addin.

I want to use this construction to open new excel application:

new Microsoft.Office.Interop.Excel.Application()

Is there a way how to pass command line arguments for example as:

string argument = "TestArgument";
new Microsoft.Office.Interop.Excel.Application(argument);

Thank you!


Solution

  • If you have to do this (I recommend running from Interop as fast as you can) you can start the Excel application and then obtain a reference to it.

    // start Excel with your command line arguments
    var pathToExcel = @"C:\Program Files\Microsoft Office\root\Office16\excel.exe";
    var commandLineArguments = "/whatever";
    System.Diagnostics.Process.Start(pathToExcel, commandLineArguments);
    
    // get a reference to it
    Microsoft.Office.Interop.Excel.Application app = (Microsoft.Office.Interop.Excel.Application)
        System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
    

    Interop is so evil that I feel almost unethical answering this. It opens the gates to endless suffering. If at all possible I recommend using something like EPPlus to interact with Excel files.