如何检查Excel是否已打开,如果是,请保存并关闭它C#

时间:2016-07-16 20:38:28

标签: c# excel process

我想检查excel是否已打开。如果是,我想保存活动工作簿并关闭excel。基本上,我的目标是杀死每个excel进程,但在此之前我想保存excel工作簿。这是我的代码......

Process[] localByName = Process.GetProcessesByName("excel");
        for (int i = 0; i < localByName.Length; i++)
        {
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            Workbook wb = xlApp.ActiveWorkbook; 
            wb.Save();  // I get an error here. "Object reference not set to an instance of an object".
            GC.Collect();
            GC.WaitForPendingFinalizers();
            wb.Close(); 
            Marshal.FinalReleaseComObject(wb);  
            xlApp.Quit();    
            Marshal.FinalReleaseComObject(xlApp);    
        }

我读到xlApp.ActiveWorkbook以只读模式获取工作簿。这可能是我的问题吗?如果是这样,请提出一个成功的方法来解决这个问题。谢谢!

1 个答案:

答案 0 :(得分:1)

&GT; Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); 这将创建Excel.Application COM对象的新实例,并且不返回活动实例。为此,请尝试

Excel.Application xlApp = null;
while(xlApp == null)
{
    try
    {
        xlApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
    }
    catch (System.Runtime.InteropServices.COMException ex)
    {
        // no more instances/error, exit out of loop
        break;
    }

    // do whatever with the instance
    Workbook wb = xlApp.ActiveWorkbook; 
    wb.Save();
    GC.Collect();
    GC.WaitForPendingFinalizers();
    wb.Close(); 
    Marshal.FinalReleaseComObject(wb);  
    xlApp.Quit();    
    Marshal.FinalReleaseComObject(xlApp);

    // set null to continue loop
    xlApp = null;
}

来源:Get instance of Excel application with C# by Handle