How to access an already opened Excel file in C#?

后端 未结 2 1389
借酒劲吻你
借酒劲吻你 2020-12-09 23:08

I have an excel workbook opened via double-clicking it in windows explorer but cannot access it in code

Excel.Application xlApp = (Application)Marshal.GetAct         


        
2条回答
  •  情深已故
    2020-12-10 00:11

    I know this thread is a little old, but I found another way of doing this. When you create a new Excel.Applicationobject you have to create the WorkBooks object. When you access an already opened Excel file, the WorkBooks object is already created, so you just need to add a new WorkBook to the existing one. @Tipx 's solution works great if you have access to the WorkBook name, but in my case the current WorkBook name is always random. Here's the solution I came up with to get around this:

    Excel.Application excelApp = null;
    Excel.Workbooks wkbks = null;
    Excel.Workbook wkbk = null;
    
    bool wasFoundRunning = false;
    
    Excel.Application tApp = null;
    //Checks to see if excel is opened
    try
    {
        tApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
        wasFoundRunning = true;
    }
    catch (Exception)//Excel not open
    {
        wasFoundRunning = false;
    }
    finally
    {
        if (true == wasFoundRunning)
        {
            excelApp = tApp;
            wkbk = excelApp.Workbooks.Add(Type.Missing);                    
        }
        else
        {
            excelApp = new Excel.Application();
            wkbks = excelApp.Workbooks;
            wkbk = wkbks.Add(Type.Missing);
        }
        //Release the temp if in use
        if (null != tApp) { Marshal.FinalReleaseComObject(tApp); }
        tApp = null;
    }
    //Initialize the sheets in the new workbook
    

    Might not be the best solution but it worked for my needs. Hope this helps someone. :)

提交回复
热议问题