How to get Excel.Application instance in C#?

2

I try to get Excel application in my code with this method:

Excel.Application xlApp = GetApplication();
if (xlApp == null) xlApp = new Excel.Application();

where

private Excel.Application GetApplication()
    {
        Excel.Application result = null;

        try
        {
            result = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
        }
        catch (System.Runtime.InteropServices.COMException ex)
        {
            //Excel is not open
        }

        return result;
    }

but the System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application") always throws exception, even when Excel application is open.

Exception: HRESULT: 0x800401E3

StackTrace:

   in System.Runtime.InteropServices.Marshal.GetActiveObject(Guid& rclsid, IntPtr reserved, Object& ppunk)
   in System.Runtime.InteropServices.Marshal.GetActiveObject(String progID)
   in RaceToolTests.UnitTest1.GetApplication() in C:\Users\...
c#
excel
interop
comexception
asked on Stack Overflow Sep 18, 2017 by KentuckyJack92 • edited Sep 18, 2017 by KentuckyJack92

2 Answers

0

Please try following code:

//import
using Excel = Microsoft.Office.Interop.Excel;

//define
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;

private void openXL()
{

    string fileName = "PATH\\FILE_NAME.xlsx"; ;

    xlApp = new Excel.Application();
    xlWorkBook = xlApp.Workbooks.Open(fileName);
    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
}
answered on Stack Overflow Sep 18, 2017 by imsome1
0

Yes it is possible to not create a new instance of Excel. Use below to get existing instance of Excel app.

var path = @"C:\Temp";
var excelFileName = $@"{path}\Sample.xlsx";

var excelApp = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application") as Excel.Application;
// Make the object visible.
excelApp.Visible = true;

// open workbook
Excel.Workbook xlWorkbook = excelApp.Workbooks.Open(excelFileName);
answered on Stack Overflow Nov 29, 2019 by Mark

User contributions licensed under CC BY-SA 3.0