关闭excel工作簿而不杀死excel进程或其他工作簿-C#

时间:2018-11-22 09:28:36

标签: c# excel process

我希望能够结束一个名为“ Microsoft Excel-test.xlsx”的任务,而不结束也是Excel应用程序的任何其他应用程序。

我用过

foreach (Process process in Process.GetProcesses())
            {
                if (process.ProcessName.Equals("EXCEL"))
                    process.Kill();
            }

但是这会杀死所有其他打开的Excel工作簿。只能杀死或结束指定的工作簿吗?

1 个答案:

答案 0 :(得分:1)

我的解决方案找到工作簿,然后将其关闭。

/// <summary>
    /// Gets the current Excel process and specified workbook and closes it.
    /// If the workbook was the only one in the application, it then closes excel as well.
    /// </summary>
    public static void CloseWorkbook()
    {
        try
        {
            Application excelApplicationProcess = (Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); // get current excel process

            foreach (object wb in excelApplicationProcess.Workbooks)
            {
                if (((Workbook)wb).FullName.Equals(Settings.Default.Test))
                    ((Workbook)wb).Close(false, Settings.Default.Test, Missing.Value);
            }

            if (excelApplicationProcess.Workbooks.Count == 0) // if it was the only one close excel as well
                excelApplicationProcess.Quit();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }