Question

I've written an Excel Addin for Office 2013 with C# language.

I know there is a few ways to open an existing Excel file, but all of them open the file in a new instance on Excel.

I have a current instance of Excel and want when somebody clicks on a button, the new file is opened in the current isctance(not a new one)!

for example I use the following piece of code:

Excel.Application excelApp = new Excel.Application();
excelApp.Visible = true;
string workbookPath = (@"C:\Downloads\Sample.xlsx");
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
    0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
    true, false, 0, true, false, false);

But this code opens the Sample.xlsx in a new instance of excel file.

Any Idea?

Thanks in advance.

Was it helpful?

Solution

Instead of creating a new object, use Marshal.GetActiveObject:

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

OTHER TIPS

Plus @LS_dev solution, I added excelApp.ActiveWorkbook.Close() command to make it work.

Excel.Application excelApp =  (Excel.Application) System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
        excelApp.ActiveWorkbook.Close();
        string workbookPath = (@"C:\Downloads\Sample.xlsx");
        Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
                0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
                true, false, 0, true, false, false);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top