2

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.

2 Answers 2

6

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

Excel.Application excelApp = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
Sign up to request clarification or add additional context in comments.

2 Comments

I used your solution but nothing changed. That still opens the file in a new instance of Excel.
This works fine to me. Can it be your Excel configuration, not allowing MDI?
3

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.