How to get Excel.Application instance in C#?

3k views Asked by At

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\...
2

There are 2 answers

3
imsome1 On

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);
}
0
Mark On

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